如何使用 Ratchet Bundle 访问 Symfony 中的会话变量?

时间:2021-03-23 14:04:25

标签: php symfony session ratchet

我正在运行一个安装了 Symfony 和 Ratchet 包的 xampp 服务器,我正在尝试从 Ratchets websocket 访问 Symfonys 会话变量,我正在尝试:

return new Message('Hello ' . $connection->Session->get('somevar'));

我收到错误:

Warning: Undefined property: Ratchet\Server\IoConnection::$Session

    Steps to reproduce:
    - Install xampp (https://www.apachefriends.org/index.html)
    - Install composer (https://getcomposer.org/)
    - Open command prompt
    - Enter the following commands
        cd C:\xampp\htdocs
        composer create-project symfony/website-skeleton new_project
        cd new_project
        composer require apache-pack
        composer req ad3n/ratchet-bundle
        php bin/console make:controller MainController
    - Add the following code to MainController.cs located in src/Controller

        #[Route('/main', name: 'main')]
        public function index(): Response
        {
           $session = new Session();
           $session->start();
    
           // set and get session attributes
           $session->set('name', 'Drak');
           $session->get('name');
           return $this->render('main/index.html.twig', [
             'controller_name' => 'MainController',
           ]);
        }

       - Create MyOwnMessageProcessor.php as documented here https://github.com/ad3n/RatchetBundle
       - Add the correct tag to config\services.yaml as documented here https://github.com/ad3n/RatchetBundle
       - Run the websocket server using "php bin/console ihsan:server:start" and navigate to localhost/new_project/main and you should see the default Symfony controller page
       - Copy and paste the following javascript into your web browsers console

var conn = new WebSocket('ws://localhost:7777');
conn.onopen = function(e) {
    console.log("Connection established!");
    conn.send('Hello');
};

conn.onmessage = function(e) {
    console.log(e.data);
};

您现在应该在命令提示符窗口中看到一个错误,指出 $Session 未定义。 我需要修改什么才能在这个 websocket 服务器中使用会话?

0 个答案:

没有答案
相关问题