如何在棘轮中加载laravel会话?

时间:2018-01-05 21:25:17

标签: laravel ratchet

我在Laravel上安装了Ratchet它的工作,但我无法读取用户会话。 我读了这个 - https://laravel.io/forum/01-16-2015-loading-laravels-session-using-ratchet 但它没有用,我有一个错误:

  

发生错误:未定义属性:stdClass :: $ request

我认为它可能与棘轮的新版本有关,因为我在2015年发表的主题上描述的决定 我的代码:

<?php

namespace App\Classes\Sockets;

use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use App\Classes\Sockets\BaseSocket;
use App;
use Auth;
use Config;
use Crypt;
use Illuminate\Session\SessionManager;
class ChatSocket extends BaseSocket {
    protected $clients;

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

    public function onOpen(ConnectionInterface $conn) {
        // Store the new connection to send messages to later
        $this->clients->attach($conn);
         $session = (new SessionManager(App::getInstance()))->driver();
         $cookies = $conn->WebSocket->request->getCookies();
         $laravelCookie = urldecode($cookies[Config::get('session.cookie')]);
         $idSession = Crypt::decrypt($laravelCookie);
         $session->setId($idSession);
         $conn->session = $session;

        echo "New connection! ({$conn->resourceId})\n";
    }

    public function onMessage(ConnectionInterface $from, $msg) {

    $from->session->start();
    // do what you wants with the session 
    // for example you can test if the user is auth and get his id back like this:
    $idUser = $from->session->get(Auth::getName());
    if (!isset($idUser)) {
        echo "the user is not logged via an http session";
    }
    // or you can save data to the session
    $from->session->put('foo', 'bar');
    // ...
    // and at the end. save the session state to the store
    $from->session->save();
    }

    public function onClose(ConnectionInterface $conn) {
        // The connection is closed, remove it, as we can no longer send it messages
        $this->clients->detach($conn);

        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e) {
        echo "An error has occurred: {$e->getMessage()}\n";

        $conn->close();
    }
}

1 个答案:

答案 0 :(得分:0)

应用相同的代码(在this page上找到它)后,我遇到了同样的问题。

问题出在这行:

$cookies = $conn->WebSocket->request->getCookies();

将其替换为以下内容:

$cookiesRaw = $conn->httpRequest->getHeader('Cookie');
$cookies = [];
if(count($cookiesRaw)) {
    $cookies = \GuzzleHttp\Psr7\parse_header($cookiesRaw)[0]; // Array of cookies
}

当然,您必须首先安装 GuzzleHttp 软件包...使用以下命令进行安装

composer require guzzlehttp/guzzle