HomePHP Page 3 - Using the Memento Pattern with a File Reading Class
Defining the signature of a caretaker class - PHP
The memento pattern can be used to maintain the state of a property that belongs to a specific class. If you want to learn more about how to do this, start reading this tutorial! Welcome to the final installment of the series "Maintaining the State of Classes." In two parts, this series teaches you how to use the memento design pattern with PHP 5, and it accompanies the corresponding theoretical concepts with diverse hands-on examples.
As you might have guessed, the functionality of a caretaker class has to be strongly related to the nature of the tasks performed by the originator. Keeping in mind this basic principle, below I listed the definition for the corresponding caretaker. In a fit of inspiration, I named it "FileDataSeeker." Take a look at it, please:
// define 'FileDataSeeker' class (in this case, this is the Caretaker class) class FileDataSeeker{ private $filePointer; // the constructor takes up the originator object as the only input parameter public function __construct(FileDataReader $fileDataReader){ $this->setFilePointer($fileDataReader); } public function setFilePointer(FileDataReader $fileDataReader){ $this->filePointer=$fileDataReader->getFilePointer(); } public function getFilePointer(FileDataReader $fileDataReader){ $fileDataReader->setFilePointer($this->filePointer); } }
As illustrated above, the "FileDataSeeker" class has some useful methods for handling the "filePointer" property that belongs to the respective originator class. These methods will help this caretaker class to carry out its responsibility to store the value of the property. Thus, the value can be retrieved at a later time. Pretty logical, isn't it?
By providing the "FileDataSeeker" class with this ability, if the file reading class locates its file pointer at a non-existent place, it will be possible to move it back to a valid position via the respective caretaker. Definitely, that makes a lot of sense!
However, showing you the originator and the caretaker separately won't give you a clear idea of how they work. Thus, in response to this issue, in the next section I'll create a simple script, which hopefully will demonstrate the power of these two classes when they operate together.
As usual, to see how this will be achieved, go ahead and read the following section. I'll be there, waiting for you.