Page 1 of 1

Scenario for Serializing an Object?

Posted: Tue Nov 16, 2010 3:21 pm
by thinsoldier
Could someone describe for me a scenario where it makes sense to serialize an object and save it in $_SESSION? I can't think of one.

Re: Scenario for Serializing an Object?

Posted: Tue Nov 16, 2010 3:28 pm
by AbraCadaver
thinsoldier wrote:Could someone describe for me a scenario where it makes sense to serialize an object and save it in $_SESSION? I can't think of one.
Scenario #1: You have an ecommerce site and your shopping cart is an object. For the cart to be available on all pages you need to save it somewhere. Many would use a session, however the PHP session handler serializes/unserializes this for you (though in a slightly different format than serialize()).

Re: Scenario for Serializing an Object?

Posted: Wed Nov 17, 2010 9:59 am
by josh
SESSION stores state. Objects bind state to behavior. When you have state bound to behavior, and the state must persist page one page load. If there is no behavior than an array makes more sense (SESSION is already an array).

Take AbraCadaver's example. You don't want to loop thru an array building up items, manually checking their quantities on every page (duplication). Nor would you even want to have to loop thru the session creating an 'item' object for the cart. (even though its less duplication, its still duplication). You could pull a regular PHP array out of the object, and save that... but thats still something you'd have to remember to do on every page load, whereas the object just gets added to the session and then is always there. The object can "decide" to change its state while we remain ignorant of it doing so.

Re: Scenario for Serializing an Object?

Posted: Wed Nov 17, 2010 3:59 pm
by Christopher
Yes the main reason, like the shopping cart example, is where you need a set of objects one multiple pages -- and the objects would require some non-trivial initialization if re-created on every page.