1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
.. object_change_tracking:
Object Change Tracking
======================
Change tracking is the process of determining what has changed in
observed objects since the last time they were synchronized with
the persistence backend.
This approach is based on `the observer pattern <https://en.wikipedia.org/wiki/Observer_pattern>`_
and consists of the following two interfaces:
* ``Doctrine\Persistence\NotifyPropertyChanged`` that is implemented by the object
whose changes can be tracked,
* ``Doctrine\Persistence\PropertyChangedListener`` that is implemented by subscribers
which are interested in tracking the changes.
Notifying subscribers
~~~~~~~~~~~~~~~~~~~~~
A class that wants to allow other objects to subscribe needs to
implement the ``NotifyPropertyChanged`` interface. As a guideline,
such an implementation can look as follows:
.. code-block:: php
<?php
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\PropertyChangedListener;
class MyTrackedObject implements NotifyPropertyChanged
{
// ...
/** @var PropertyChangedListener[] */
private $listeners = [];
public function addPropertyChangedListener(PropertyChangedListener $listener) : void
{
$this->listeners[] = $listener;
}
}
Then, in each mutator of this class or any derived classes, you
need to notify all the ``PropertyChangedListener`` instances. As an
example we add a convenience method on ``MyTrackedObject`` that shows
this behavior:
.. code-block:: php
<?php
// ...
class MyTrackedObject implements NotifyPropertyChanged
{
// ...
final protected function notifySubscribers(string $propertyName, $oldValue, $newValue) : void
{
foreach ($this->listeners as $listener) {
$listener->propertyChanged($this, $propertyName, $oldValue, $newValue);
}
}
public function setAge(int $age) : void
{
if ($this->age === $age) {
return;
}
$this->notifySubscribers('age', $this->age, $age);
$this->age = $age;
}
}
You have to invoke ``notifySubscribers()`` inside every method that
changes the persistent state of ``MyTrackedObject``.
The check whether the new value is different from the old one is
not mandatory but recommended. That way you also have full control
over when you consider a property changed.
|