Question

I am newbie to Ratchet and Symfony both. I am trying to get familiar with them. I have used alternative to sessions which is quite weird but works. Here's it:

In JS (a native PHP session)

name = "<?php echo $_SESSION['name']; ?>";
msg = elem.value;
socket.send(name+"|"+msg);

The sent argument is then explode with delimiter |. It creates two strings. One is the name and other is msg which is then sent to all connections except the sender.

list($name, $message) = explode("|", $msg);

How can I use Symfony Session which saves nickname when user enters it and it will be accessible by my Chat class in MyApp namespace?

I have API docs but there is no simple example for using session. API Documentation.

Tree:

/www
 |
 |___/src
 |    |
 |    |____/MyApp/
 |           |
 |           |___Chat.php // The Chat Class
 |
 |___/bin
 |     |
 |     |___chat-server.php
 |
 |___/vendor
 |
 |___/chat.php // <-- Chat Room, sending and receiving here
 |
 |___/index.php // <-- Ask for nickname here
 |
 |___/composer.phar
 |
 |___/composer.lock
 |
 |___/main.js // <-- Index HTML javascript
 |
 |___/socket.js // <-- Websocket handler for char.php
 |
 |___/main.css // <-- All style
Était-ce utile?

La solution

A controller can set the nickname to in the session:

/**
 * @Route("/hello/{nickname}")
 */
public function indexAction($nickname)
{
    $session = $this->getRequest()->getSession();
    $session->set('nickname', $nickname);
}

To retrieve the nickname in your Chat app,

public function onOpen(ConnectionInterface $conn) 
{
    $nickname = $conn->Session->get('nickname');
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top