PHP developers frequently need to maintain the state of an object across several web pages. There are a number of ways to do this. In this article, the first of two parts, you will learn how to handle this task with the memento pattern.
As the seasoned PHP developer that you certainly are, you'll probably know that one of the easiest ways to track and maintain the state of several variables across different HTTP requests is by using the neat capabilities of sessions. These have been included for a long time with the different PHP distributions.
Moving toward PHP object-oriented programming, it's easy to maintain the state of a certain object across several web pages because a single instance of a class can be also stored onto a typical session variable.
While the above mentioned process is one of the most common tasks that a PHP programmer has to tackle when developing a web application, it is fair to say that an object can also be tracked by using a design pattern. Logically, at this moment you're wondering: what pattern is capable of doing that? Well, I'm glad you asked, since the answer to your question is the memento pattern.
To put it simply, when this pattern is used in the context of a given application, two classes are involved: the first one is called the originator, while the second one is denoted the caretaker. Despite the funny names assigned to these classes, which may lead one to think that this pattern is rather useless, the truth is that it can be pretty handy for holding the state of a particular class.
In accordance with the schema of classes that I described a few lines above, the caretaker would be responsible for maintaining the state of the originator by using one or more methods. However, the implementation of this pattern is particularly interesting, since the caretaker object will keep track of the state of the originator by using only the interface of the originator.
Does this definition sound confusing? Don't you worry about it for the moment, because in this two-part series, I'm going to demonstrate with numerous code samples how to apply the memento pattern so that it can be used within your own PHP applications with only minor problems.
Having defined the goal of this new series, come with me and learn how to implement this useful pattern with PHP 5. Do we have a deal? Okay, let's get started.