Introducing the Memento Pattern - Creating the first piece of the memento pattern
(Page 2 of 4 )
As I clearly explained in the introduction of this article, when it comes to applying the memento design pattern it's necessary to define two classes, called the originator and the caretaker respectively. In this tutorial, I'm going to demonstrate how to use the pattern by creating the originator first, and then the caretaker.
In this case, the functionality housed within the originator will involve traversing an array structure, which will be directly inputted into the class via its constructor.
Having explained briefly how the originator class will work, take a look at its corresponding definition. It is as follows:
// define 'ArrayProcessor' class (in this case, this is the Originator class)
class ArrayProcessor{
private $inputArray;
private $arrayIndex;
// set input parameters
public function __construct($inputArray,$arrayIndex=0){
if(!is_array($inputArray)){
throw new Exception('Invalid input array!');
}
if($arrayIndex<0||$arrayIndex>(count($inputArray)-1)){
throw new Exception('Invalid index value for input array!');
}
$this->setInputArray($inputArray);
$this->setArrayIndex($arrayIndex);
}
// set input array
public function setInputArray($inputArray){
$this->inputArray=$inputArray;
}
// fetch input array
public function getInputArray(){
return $this->inputArray;
}
// set value for 'arrayIndex' property
public function setArrayIndex($arrayIndex){
$this->arrayIndex=$arrayIndex;
}
// get value of 'arrayIndex' property
public function getArrayIndex(){
return $this->arrayIndex;
}
// fetch array element according to array index
public function getArrayElement(){
if(!$elem=$this->inputArray[$this->arrayIndex]){
throw new Exception('Error fetching element of input array!');
}
return $elem;
}
}
As you'll realize, the signature of the above "ArrayProcessor" class is pretty straightforward. In this case, the class has been defined as the originator. It presents some simple methods for traversing a given array via an index parameter, which is also inputted through the respective constructor.
Aside from describing the core tasks performed by the aforementioned originator class, there's not much to be said about it (at least for the moment). However, don't feel disappointed, since this is only the first building block of the memento pattern.
As you learned before, there's another class involved in this schema: the caretaker class. In the next section I'm going to create this new class and show you how it can hold a specific state of the previous originator. Please click on the link below and keep reading.
Next: Building the second piece of the memento pattern >>
More PHP Articles
More By Alejandro Gervasio