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


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 Redis();
$redisClient->connect('localhost', 6379);
$redisClient->set($_SERVER['REQUEST_URI'], $this->page);
$redisTest = $redisClient->get($_SERVER['REQUEST_URI']);

However, with this code the value of the URL key that is being stored in Redis is type of string with the value equal to 'Object' instead of the actual PHP object. Is there a way to store a PHP object without serializing it?

As you can see in Redis data types, Redis only supports these 5 data types:

  • Stirng
  • List
  • Set
  • Hash
  • Sorted Set

So, there is no object data-type and therefor you are not able to store an object directly as a value. You have to serialize it first (or JSON-encode it with the json_encode function for example).

Is there any problem with serializing that you insist on storing your objects directly?

Update: According to what you said in the comments, you can use the approach indicated in this answer

So you can use:

$xml = $simpleXmlElem->asXML();

before serialization, and then after unserialize(), use the following code:

$simpleXmlElem = simplexml_load_string($xml);

In this way, you don't have to serialize a PHP built-in object like SimpleXmlElement directly and there will be no problems.