Symfony:以JSON存储会话

问题描述 投票:0回答:1

在我的Symfony应用程序中,我使用NodeJS和socket.io来构建聊天功能并发送实时通知。为此,我使用Redis以JSON格式存储会话,因此可以在Javascript中轻松解析。

public function read($session_id) {
    $tmp = $_SESSION;
    $_SESSION = json_decode($this->client->get(self::PREFIX . $session_id), true);

    if (isset($_SESSION) && !empty($_SESSION) && $_SESSION != null) {
        $encoded_data = session_encode();
        $_SESSION = $tmp;

        return $encoded_data;
    }

    return '';
}

public function write($session_id, $session_data) {
    $tmp = $_SESSION;
    session_decode($session_data);
    $decoded_data = $_SESSION;
    $_SESSION = $tmp;

    $this->client->setex(self::PREFIX . $session_id, $this->ttl, json_encode($decoded_data));

    return true;
}

问题是会话未正确编码,尤其是用户信息(身份验证部分)。

Symfony存储会话:

"_sf2_attributes|a:2:{s:18:\"_csrf/authenticate\";s:43:\"Fc3iwpceqYiNmAn1FbUyQyaEPdu7qbI_unu5dBAgaTg\";s:14:\"_security_main\";s:456:\"C:74:\"Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken\":368:{a:3:{i:0;N;i:1;s:4:\"main\";i:2;s:328:\"a:4:{i:0;C:21:\"AppBundle\\Entity\\User\":127:{a:5:{i:0;i:52;i:1;s:12:\"user123\";i:2;s:60:\"$2y$13$mgT//whXPFsj7b0XCAWhdeiC2oGZqojiAzky.6sThuN6MI9zALt1.\";i:3;i:1;i:4;i:1;}}i:1;b:1;i:2;a:1:{i:0;O:41:\"Symfony\\Component\\Security\\Core\\Role\\Role\":1:{s:47:\"\x00Symfony\\Component\\Security\\Core\\Role\\Role\x00role\";s:9:\"ROLE_USER\";}}i:3;a:0:{}}\";}}\";}_sf2_flashes|a:0:{}_sf2_meta|a:3:{s:1:\"u\";i:1524485577;s:1:\"c\";i:1524485576;s:1:\"l\";s:1:\"0\";}"

JSON编码会话:

"{\"_sf2_attributes\":{\"_csrf\\/authenticate\":\"hvNt4SQIm7IArE57JgHyuVSCLlt4hrw1D-PVC_kBfKA\",\"_security_main\":\"C:74:\\\"Symfony\\\\Component\\\\Security\\\\Core\\\\Authentication\\\\Token\\\\UsernamePasswordToken\\\":368:{a:3:{i:0;N;i:1;s:4:\\\"main\\\";i:2;s:328:\\\"a:4:{i:0;C:21:\\\"AppBundle\\\\Entity\\\\User\\\":127:{a:5:{i:0;i:52;i:1;s:12:\\\"user123\\\";i:2;s:60:\\\"$2y$13$mgT\\/\\/whXPFsj7b0XCAWhdeiC2oGZqojiAzky.6sThuN6MI9zALt1.\\\";i:3;i:1;i:4;i:1;}}i:1;b:1;i:2;a:1:{i:0;O:41:\\\"Symfony\\\\Component\\\\Security\\\\Core\\\\Role\\\\Role\\\":1:{s:47:\\\"\\u0000Symfony\\\\Component\\\\Security\\\\Core\\\\Role\\\\Role\\u0000role\\\";s:9:\\\"ROLE_USER\\\";}}i:3;a:0:{}}\\\";}}\"},\"_sf2_flashes\":[],\"_sf2_meta\":{\"u\":1524651793,\"c\":1524651793,\"l\":\"0\"}}"

Symfony不使用PHP内置存储机制吗?我在这做错了什么?

任何帮助是极大的赞赏。

php json symfony session redis
1个回答
0
投票

在会话中存储更简单的方法:在客户端实体中实现\ Serializable然后编写序列化和反序列化函数示例:

class Client implements \Serializable{
public function serialize()
{
    return serialize([
        $this->id,
        $this->name,
        $this->color
    ]);
}

public function unserialize($serialized)
{
    list (
        $this->id,
        $this->name,
        $this->color
        ) = unserialize($serialized);
}}

在此之后你几乎可以在任何地方使用它

$this->session->set('client',$client);
$this->session->get('client');

添加要序列化和反序列化函数的任何其他必填字段

© www.soinside.com 2019 - 2024. All rights reserved.