Object Persistence in PHP?

Just wondering about this (there is probably a not too difficult answer to this, but I can’t seem to find the answer online :()

How do you keep an object across multiple pages? Say you have a class called Users that pretty much models everything about a user (user name, user id, age, location, user type etc etc.) and you query the database based on the user’s login to form the object then store the user_id as a session information. The user clicks on the send a message link, and you’ll have to read the user_id for the session and query the database again.

Is there a better way of doing this, or is my concept totally wrong to begin with?

Thanks :slight_smile:


Due to the transaction-less nature of the web, you require these sessions along with session keys to keep track of your users. If you were to keep an object persistent, it would be no different than storing the information in the session (although be weary of security) or simply query the db at each request.

Since most pages require some db transaction, you won’t suffer a serious hit to your server(s) and by abstracting the code into an include, you can avoid repetition.

e.g. header.inc.php

if (isset($_SESSION[‘uid’]))
$GLOBALS[‘user’] = db_find_user_by_id($_SESSION[‘uid’]);

hope this helps.

Object persistence is possible. You can serialise an object for storage (either to a file or in the session super global) and unserialise when you need it.



You shouldn’t be afraid of querying the database again on each request. That’s the nature of PHP-applications, and any loss of efficiency is made up for by other means. Sessions are not meant to be used for caching persistent data. Most likely, it’s going to be slower than querying the database anyway, since sessions are file-based. Databases on the other hand, are intelligent enough to cache recent results in memory.

Gah!! guess who’s refactoring a year old module then :stuck_out_tongue: (yes, me :)).

It was something I picked out from php.net and was actually a proof of concept that had made its way into actual production code.

I was totally unaware that this is the wrong way of doing things. I use it for an insignificant part of an old application I’ve made (a shopping cart-like object), I never really revisited or even had to touch it since it worked the whole time.

In light of kyber’s correction, while it IS possible to persist objects in sessions or files, it’s discouraged that you do so.


Hmmm, then wouldn’t it be easier if you just used cookies to store a person’s user id instead of using PHP’s session handling?

And if PHP’s session management is ran off a file (I remember reading that somewhere), wouldn’t it be grossly inefficient to run a site like say, wikipedia?

The difference between using a cookie and PHP-sessions, is that data stored in the session are only accessible from the server side script. So you can put trusted information in there.

For very large scale systems, you can set up sessions to be stored in a database instead, which makes it possible to distribute the load across multiple servers. But it’s still set up and torn down on a per request basis.

The performance issue isn’t the biggest problem with the use of sessions though. If you pull data out of the database and put it in session, you have two copies of the data. This is something that you generally want to avoid in software, since it leads to concurrency issues. With web applications, the problem is even greater. The nature of the web is stateless, but if you store application state in sessions, you break this feature. This means that your users can’t bookmark pages, or use the back-button of the browser. You may also get unexpected behaviour if the user has multiple windows open to the same application. As a general rule of thumb, try to minimize use of sessions, and try to use query-parameters to maintain application state.

On the flipside - If your application is completely stateless, it’s very easy to appply caching techniques on top of it.

Or you can use memcache servers or something similar like shmop to manage often accessed data, which will generally be a lot faster than either db or file access… if your site does in fact need that level of performance. You’ll probably hit on other bottlenecks before needing shared mem access, however if you get to the level of millions of daily hits, there’s a pointer :wink:


> …, however if you get to the level of millions of daily hits, there’s a pointer

I doubt that if you have millions of visitors, shared memory would have any real benifit to you, in regards to tackling any performance issues you would be facing. I’m not saying that there isn’t a benifit, not at all; But with the shear amount of resources required to satisfy that amount of users, shared memory alone wouldn’t be enough.

If you have millions of requests then you are looking at scaling with hardware for the most part. If you scale horizontally, then you’d be looking to scale your application at the same time. With an LAMP architecture that is what you’d be working towards anyways…

You can serialize an [url=http://au2.php.net/manual/en/language.oop.serialization.php]object to make it a string, and you can [url=http://au.php.net/unserialize]unserialize when you need to restore.

Actually the best is to keep the users ID in the session and retrieve the information from the database each time you need it.
Basicly, if you take the info and put it all in a session you risk to have different data between the “session user” and the “database user”.
In his session time the user may have got a higher ranking, or more forum posts, than depicted in the session.


You’d be surprised at just how much something like memcache can boost performance, especially when dealing with a DB and session hungry application. Obviously you’re probably going to need to scale out horizontally if you’re coping with that much traffic, but in past experience it has definitely helped to remove bottlenecks caused by calls to session_start.

Thanks people for explaining :slight_smile:

We’ll never ever reach more than a million hits a day, so no worries about that :wink: But I suppose those slightly more pedantic can have their fun :slight_smile:

Haven’t though of this before, good point. Session should save as few data as possible since its not lazy and everything is available anytime…
thanks for the hint!!

As everyone else here has stated it’s very well possible to create some type of “object persistance” in php, however I’d say that it’s both uneccessary and very counter intuative to php’s way to do things(build up, tear down).

Also, for example in Java it’s very common with object persistance - but my whole stance on this it’s very counter intuative to go against the statelessness of the http protocoll.

Just my 0.02$

but my whole stance on this it’s very counter intuative to go against the statelessness of the http protocoll.

You go against this all the time in PHP, you are just using the database and the file system instead of memory. In Java its rather nice that you can store local caches, configuration details and sessions in memory, whereas with PHP you can used memcached but it is running in a seperate prcoess and is less efficient.

For some applications having the ability to persistent objects can make the application much faster than anything you could do with PHP. This gives the user a better experience. On the other hand its less useful for applications that are dealing with large amounts of data that can’t easily be cached (most successful large php applications seem to be of this type).

I wonder if real object persistence in PHP is possible (?) Is there any extension that would provide this functionality?
By real I mean that you save object as it is (no serialization) and take it in next page load… literally you keep object from being gone from memory when script finishes it’s execution.
I don’t know well php internals - I’m not sure would it be technically possible… (if not - why?)

I have problem… as I want to cache object which is an instance of class that is extension of php internal class - thus it cannot be serialized - heck I’m unable to cache it
…at least i need to write my own serialize method for this case and that won’t be very efficient.

No. PHP is designed to set up, execute, and tear down on each request. There is no memory shared between requests. And even with shared memory modules, such as memcached or apc, it can only be used to put primitive data into; You can’t use it to keep an instance of a class, because that is tied to the process, which is going to die with the request.

It’s important to realise that this is not a limitation of PHP. It’s a feature, not a bug. Not only is it a good idea from a technical pov, since it makes PHP very scalable, but it also forces developers to write stateless applications. Since the HTTP protocol is stateless, this is a good match for web applications.

Lately I found out that the functions serialize and unserialize take very much time :x. After some tests I found that the old var_dump takes much less time, and since it is pure PHP later is faster to retrieve :slight_smile:

This is more a question of interpretation, but while I think Object persistance in PHP is a bit iffy and sometimes counter-intuative persisting data to a filesystem and/or database is not the same thing(yes, I’m aware that objects also contain/are data, but as I said my statement is kinda of open for interpretation)

What PHP looses in terms of speed when it comes to object persistance it often makes up in other areas. Also, as soon as an application grows a bit the amount of data handled escalades quickly and caching becomes harder and harder.

Couldn’t have put it better myself.