Design Patterns PHP - Memento Java

1) What have we done?

We created object "Memento" which has record of stated object "ClassA"

"Memento" contains two methods "setState" and "getState" in order to return stated of given object.
In "ClassA" we created two methods:
- "createMemento" for store current state of object
- "setMemento" to inject previous state.


class Memento
{
    /**
     * @var array
     */
    protected $state;

    /**
     * @param array $state
     * @return Memento
     */
    public function setState($state)
    {
        $this->state = $state;

        return $this;
    }

    /**
     * @return array
     */
    public function getState()
    {
        return $this->state;
    }
}

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;
    }

    public function createMemento()
    {
        return (new Memento())->setState(['attribute' => $this->attribute]);
    }

    public function setMemento(Memento $m)
    {
        $state = $m->getState();
        $this->attribute = $state['attribute'];
    }
}




2) Is our goal was achieved?

Definitely yes, let's see on Client

We just create "Memento" before "setAttribute" and after it we restore previous state.


$classA = new ClassA('value1');

$memento = $classA->createMemento();
$classA->setAttribute('value2'); // wa want possibilitu of undo this action
$classA->setMemento($memento);

$classA->doSomething();