Connections

A Connection is a PHP object that represents a client connected to your server. The object has properties that contain information about the client. The more Component classes the Connection is passed through, the more properties will be attached to it. For example, you may or may not use the SessionProvider in your application stack. If you choose to use it, each connection will have a Symfony2 Session class attached to it you can access like this:

$hello = $conn->Session->get('hello');

If you do not include the SessionProvider in your application stack, there will be no Session variable accessible in a connection.

If you're in your development environment and curious to see what's attached to a Connection object, just var_dump it! (Each component [links on left sidebar] documents which parameters it adds to each Component, if you don't want to var_dump during your testing.

Connection Functions/Methods

From the ConnectionInterface you can see each Connection will contain a send and close method. These two methods will send a string to the client or close the connection, respectively.

However, depending on the Components you use in your application there could be more methods available to call on Connections This information is documented under each Component, accessible from the left menu bar.

Containers

Even though Connection objects are passed to your application on every event trigger, it's usually a good idea to store your connections in a container, to reference later. The purpose of this is to interact, or push, to a Connection even though that Connection may not have triggered an event. We suggest using a SplObjectStorage to keep your connections; however, a standard array will do. SplObjectStorage classes are often easier to work with when dealing with objects, as there is no lookup required:

<?php
use Ratchet\Resource\ConnectionInterface;

class MyApp {
    protected $connections;

    public function __construct() {
        $this->connections = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn) {
        $this->connections->attach($conn);
    }

    public function onClose(ConnectionInterface $conn) {
        $this->connections->detach($conn);
    }
}