views:

234

answers:

2

I have nested PHP objects that I would like to save in memcache. Can I use json_encode(), json_decode() to store/retrieve the data from memcache?

Implicit in the question is whether the json_encode() function is "clever" enough to introspect my objects without me having to explicitly define the structure.

if json_encode() is not the way to go, how can I store my nested objects in memcache?

+3  A: 

Use serialize/unserialize for this.

That works nicely for "nested objects". There are also 2 magic methods called __wakeup() and __sleep() that will be called whenever you serialize/unserialize an object. Here you can perform additional stuff like: close/re-open file/db-handles, etc. That's something that you don't get with json.

Json would work as well, but it's better and faster to use the PHP serialization methods as they are built just for this purpose.

André Hoffmann
No need for double serialization as memcache does this on the fly.
Miha Hribar
+1  A: 

FYI the memcache client does serialize/unserialize on the fly while operating with memcached servers, so an additional serialize/unserialize is not needed. There is quite some overhead accompanied with serialization (if memory size is a problem) so you could move on to the newer memcached client (notice the additional d on the end of the client name) that has support for igbinary.

Miha Hribar