Is it common practice to save PHP objects by storing them in session variables?

I am new to OOP using PHP, and the idea seems a bit pointless in some ways. In languages ​​that are not associated with websites, the object lives during the life of the program (from execution to release). In this situation, this makes sense because you create a class and then initialize it at runtime, where you can access it often as needed afterwards. However, with web programming, since the execution of the application can occur at different stages (loading pages), the life of the object can be only a small part of the time when the application starts. Therefore, it seems to me that the only option for saving objects in the process of using the application is to save this object after initialization in a session variable. Is this a common practice or are there other ways to make better use of the power of OOP in PHP?

+8
php
source share
3 answers

There is an article on the PHP website specifically dedicated to this: Serializing Objects - Objects in Sessions . There is nothing wrong with serializing objects in your session, but as suggested in this article:

It is highly recommended that the application serializes objects, for future use the application, so that the application includes a class definition of this object throughout the application. Do not do this. The result is a non-serializable object without a class definition ...

+8
source share

This can be very useful for managing objects with short time limits. Perhaps you want to communicate with two different types of database servers - having objects that can create queries for these database servers can be very convenient. You, the programmer, can interact with them the same way, but behind the scenes you can use the unix domain socket to talk to the local PostgreSQL, and the other can use the TCP connection from the session pool to talk to the Oracle instance,

Object-oriented programming exists to provide encapsulation and abstraction. Both of them are useful, even if the objects involved are created, live and die, after 0.5 seconds.

+2
source share

With PHP, you cannot keep an object alive, so you cannot save it in a session to get performance. PHP will always serialize the object when writing to the session and deserialize its reading from the session.

To answer your question, yes, it is very common for storing an object in a session, but not for performance reasons. The storage and reading from the session is very quiet, so I would only look at the optimization there if you are sure that this is a bottleneck.

+1
source share

All Articles