开发者

Is it advisable to use serialize() to persist an object across multiple requests?

开发者 https://www.devze.com 2023-01-08 10:00 出处:网络
In a project I\'m working on, I have an object that is a sort of Collection with a database b开发者_开发知识库ack end.The exact results this Collection returns are dependent upon its configuration, wh

In a project I'm working on, I have an object that is a sort of Collection with a database b开发者_开发知识库ack end. The exact results this Collection returns are dependent upon its configuration, which is itself dependent on a number of user inputs. I would like to have an element on the page that contains the records in the Collection and can be updated dynamically through an AJAX request. The idea has occurred to me to serialize() this object, store it in memcache, and include the memcache key as a parameter in my AJAX calls. I would then retrieve the string from memcahce, unserialize() it, and retrieve the next set of records from the collection.

Is this a good way to achieve the kind of object persistence I want to make this work? I considered storing just the configuration, but I feel like this is a better "set it and forget it" solution in the face of future changes to the user controls. My main concern is that there might be some pitfall with serialize that I'm not aware of that would make this solution not robust, unreliable, or not very fast. Do I need to be concerned in any of those regards?


serialize/unserialize works well enough with scalars, but can be more problematic when working with objects. I've had a couple of issues that highlight potential pitfalls.

If any of your object properties are resources, these can't be serialized. You'd need to use the magic __sleep and __wakeup methods to cleanly close the resource attribute and restore it again on unserialize.

If your collection contains objects with cyclic references (e.g. a cellCollection object is an array of cell objects, each of which has an attribute pointing back to the parent cellCollection object) then these won't be cleanly restored on unserialize... each cell's parent object will actually be a clone of the original parent. Again, __sleep and __wakeup need to be used to restore the true relationships (not a trivial task).


If the serialized objects are larger than just queries you are extracting from the database, and have had a lot of processing applied to them, then what you are proposing is actually a very good optimization.

Two reference in particular: http://code.google.com/p/memcached/wiki/FAQ#Cache_things_other_than_SQL_data! http://www.mysqlperformanceblog.com/2010/05/19/beyond-great-cache-hit-ratio/

Both promote using memcached as being beyond a "row cache".

0

精彩评论

暂无评论...
验证码 换一张
取 消