I have looked at several tutorials and looked at the Symfony, and Ratchet API documents but I can't get the session data in my Chat class (WebSocket server Application).
I set the session data when the user hits the web page:
<?php
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;
require 'vendor/autoload.php';
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);
$storage = new NativeSessionStorage(
array(),
new MemcacheSessionHandler($memcache)
);
$session = new Session($storage);
$session->start();
$session->set('id', $user_id);
print_r($session->all());
# Array ( [id] => 1 )
I start the WebSocket server by command line (php ./server.php
):
<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use MyApp\Chat;
$ip = "127.0.0.1";
$port = "8080";
# Change the directory to where this cron script is located.
chdir(dirname(__FILE__));
# Get database connection.
require_once '../../includes/config.php';
require_once '../../vendor/autoload.php';
$memcache = new Memcache;
$memcache->connect($ip, 11211);
$session = new SessionProvider(
new Chat,
new Handler\MemcacheSessionHandler($memcache)
);
$server = IoServer::factory(
new HttpServer(
new WsServer(
$session
)
),
$port,
$ip
);
$server->run();
In my MyApp\Chat application, I try to get the session data I set but it returns NULL
:
<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface
{
protected $clients;
private $dbh;
public function __construct()
{
global $dbh;
$this->clients=array();
$this->dbh=$dbh;
}
public function onOpen(ConnectionInterface $conn)
{
$this->clients[$conn->resourceId] = $conn;
echo "New connection! ({$conn->resourceId})\n";
print_r($conn->Session->get('name'));
# NULL
}
}