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

Sai Wai Maung picture Sai Wai Maung · Nov 3, 2014 · Viewed 19k times · Source

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']);
var_dump($redisTest);

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?

Answer

Aliweb picture Aliweb · Nov 3, 2014

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

  • String
  • 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.