php-redis - Is there a way to store PHP object in Redis without serializing it?

前端 未结 4 834
我寻月下人不归
我寻月下人不归 2021-02-14 17:10

I am trying to store user\' request URL as the key and a PHP object corresponding to that key as the value in Redis. I tried the following:

$redisClient = new Re         


        
4条回答
  •  长发绾君心
    2021-02-14 17:34

    Serializing would be the most straightforward way.

    An alternative is to json_encode only the parameters required to reconstruct the object later. One way to do this is using PHP 5.4's JsonSerialize interface. You'd want to extract various properties using jsonSerialize and then provide the means to pass them back into your class when you pull the item from Redis.


    class MyPage implements JsonSerializable
    {
    
        protected $p1;
        protected $p2;
    
        /**
         * @param mixed $p1
         */
        public function setP1($p1)
        {
            $this->p1 = $p1;
        }
    
        /**
         * @param mixed $p2
         */
        public function setP2($p2)
        {
            $this->p2 = $p2;
        }
    
        /**
         * (PHP 5 >= 5.4.0)
    * Specify data which should be serialized to JSON * @link http://php.net/manual/en/jsonserializable.jsonserialize.php * @return mixed data which can be serialized by json_encode, * which is a value of any type other than a resource. */ public function jsonSerialize() { return [ 'p1' => $this->p1, 'p2' => $this->p2, ]; } }

    In this way you're easily able to reconstruct from JSON. You could add a helper method to do that or just call the setters.

提交回复
热议问题