3

As you know, when you store a class defination in SESSION serialized automatically, and are unserialized on each following pages.

I just started to write classes and I wonder that: to store a class in session or a file with serializing is a good idea?

If yes, how can I STORE and then GET to use a class in PHP5?

hakre
  • 193,403
  • 52
  • 435
  • 836
kuzey beytar
  • 3,076
  • 6
  • 37
  • 46

3 Answers3

2

You don't store a class in a session variable, but you can store an object. Take note that if your object has properties referring to resources like file handles and database connections, no amount of unserializing will bring them back.

bcosca
  • 17,371
  • 5
  • 40
  • 51
2

Unless it's a tiny class, probably not (see this question for possible pitfalls with large sessions). In short, sessions are not designed to be a caching mechanism, and they don't perform too well when you make them into one.

Note that if you are using the default session handler, your sessions are stored on the hard drive - not very fast when you get many concurrent requests. Also (test and measure), serialization/deserialization may be slower than the normal methods of object creation - note that you'd probably be deserializing twice: from session to string, then string into object of that class.

If you want to go the serialization/deserialization route, try e.g. Memcached instead.

Community
  • 1
  • 1
Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222
1

Storing object instances in the session has the following disadvantages:

  • Performance overhead: Even if you don't need some objects, the will be unserialized and instatiated on every request.
  • Strange bugs in development: Whenever you add or remove a property from an object, the instance from the session will not match the object definition.
  • Security: Typically the session data is stored separately from your application. Sometimes this location is not as access-protected and secure as the rest of your files.
  • Data duplication and wrong state: With sessions you may store the same objects over and over again for different users. Compared to a dedicated object cache, where each object is only stored once, this leads to increased storage needs and the possibility that an object has the wrong state because the state was changed in another session.

I'd rather store the objects in a dedicated cache. Have a look at the Zend Cache class as an example of a good cache library.

If your object uses resources (database connections, files, gd images) your class should implement the Serializable interface. You then have to add two methods that do cleanup and initialization stuff.

chiborg
  • 26,978
  • 14
  • 97
  • 115