Design Patterns PHP - Memento Java

1) What have we got at the beginning?

We have a simple class "ClassA" with an one attribute(with setter and set by constructor)


class ClassA
{
    /**
     * @var string
     */
    protected $attribute;

    /**
     * @param  string $attribute
     */
    function __construct($attribute)
    {
        $this->attribute = $attribute;
    }

    public function doSomething()
    {
        echo 'doing something with attribute: ' . $this->attribute . PHP_EOL;
    }

    /**
     * @param string $attribute
     * @return ClassA
     */
    public function setAttribute($attribute)
    {
        $this->attribute = $attribute;

        return $this;
    }
}




We have some state of this objects (which is defined by attributes) for clarity in our example is only on attribute.

2) What is our goal?

Let's see client.


$classA = new ClassA('value1');

$classA->setAttribute('value2'); // wa want to possibility of undo this action

$classA->doSomething();




we have simple three steps here:
- first we created object of "ClassA" with "value"
- then we change state - by calling setter
- finally we call some business action

We would like to have possibility of undoing changing state

3) How we can do this?

For this purpose is created "Memento" pattern in which we save states of "ClassA" let's see this in step2