The HTTP protocol is stateless, but sometimes it is necessary to make web applications store or remember information. This is sometimes referred to as persistent storage, and it takes on a number of different forms. This six-part series of articles will explain the concept and show you various ways to give your web applications a memory.
Very often, you’ll hear web developers to say (sometimes with a subtle sense of arrogance) that a certain application uses a persistent storage mechanism to save the data it needs to work properly. This is nothing but an elegant way to say that a web program uses a relational database, a simple text file or even a single cookie, to store pieces of data across different HTTP requests.
The stateless nature of the HTTP protocol frequently requires working with these storage mechanisms, even in their simplest form. Moreover, if you’ve developed a few web-based programs that interact with MS SQL, MySQL, or an Oracle database, then you’ve already created persistent data layers, whether or not you realized it.
Unquestionably, when using PHP 5 the most common type of persistent storage system associated with the language is one or multiple MySQL databases, but as I said before, cookies and plan text files also fall under this category. Typically, though a persistent storage mechanism will store chunks of data that don’t have an explicit meaning when analyzed separately, such as strings or numbers, it’s also possible to save entire objects, or a particular state of those objects.
This possibility brings to the table the concept of persistent objects, or objects that are capable of maintaining themselves or their state across several HTTP requests. The best part is that these objects are much simpler to create than you might think; the creation process requires only an intermediate background in using the object-oriented paradigm with PHP 5, as well as a basic idea of how to serialize and unserialize objects. That’s all you’ll need, really.
So, in this set of articles, I’m going to explain, with code samples, how to build persistent objects in PHP 5. First we'll use simple cookies to “persist,” and once you've properly digested the the key concepts, I’ll utilize text files, and finally, a single MySQL database table.
Finally, I’d like to say that some of the classes that I’m going to build in the subsequent tutorials of this series will be inspired partially by the example class developed by Martin Jansen in its excellent article on Object Overloading in PHP 5. Kudos to him for that.
Having clarified that point, let’s leave the boring theory behind and start learning the basics on creating persistent objects. Let’s begin right away!