Implementing the Notify ChangeTracking Policy

The NOTIFY change-tracking policy is the most effective change-tracking policy provided by Doctrine but it requires some boilerplate code. This recipe will show you how this boilerplate code should look like. We will implement it on a Layer Supertype for all our domain objects.

NOTIFY 変更追跡ポリシーは、Doctrine が提供する最も効果的な変更追跡ポリシーですが、ボイラープレート コードが必要です。このレシピは、この定型コードがどのように見えるべきかを示しています。すべてのドメイン オブジェクトのレイヤー スーパータイプに実装します。

Note

ノート

The notify change tracking policy is deprecated and will be removed in ORM 3.0. (Details)

通知変更追跡ポリシーは非推奨であり、ORM 3.0 で削除されます。(詳細)

Implementing NotifyPropertyChanged

The NOTIFY policy is based on the assumption that the entities notify interested listeners of changes to their properties. For that purpose, a class that wants to use this policy needs to implement the NotifyPropertyChanged interface from the Doctrine\Common namespace.

NOTIFY ポリシーは、エンティティが関心のあるリスナーにプロパティの変更を通知するという前提に基づいています。そのために、このポリシーを使用したいクラスは、Doctrine\Common 名前空間から NotifyPropertyChanged インターフェースを実装する必要があります。

<?php
use Doctrine\Persistence\NotifyPropertyChanged;
use Doctrine\Persistence\PropertyChangedListener;

abstract class DomainObject implements NotifyPropertyChanged
{
    private $listeners = array();

    public function addPropertyChangedListener(PropertyChangedListener $listener) {
        $this->listeners[] = $listener;
    }

    /** Notifies listeners of a change. */
    protected function onPropertyChanged($propName, $oldValue, $newValue) {
        if ($this->listeners) {
            foreach ($this->listeners as $listener) {
                $listener->propertyChanged($this, $propName, $oldValue, $newValue);
            }
        }
    }
}

Then, in each property setter of concrete, derived domain classes, you need to invoke onPropertyChanged as follows to notify listeners:

次に、具体的な派生ドメイン クラスの各プロパティ セッターで、通知リスナーに次のように onPropertyChanged を呼び出す必要があります。

<?php
// Mapping not shown, either in attributes, annotations, xml or yaml as usual
class MyEntity extends DomainObject
{
    private $data;
    // ... other fields as usual

    public function setData($data) {
        if ($data != $this->data) { // check: is it actually modified?
            $this->onPropertyChanged('data', $this->data, $data);
            $this->data = $data;
        }
    }
}

The check whether the new value is different from the old one is not mandatory but recommended. That way you can avoid unnecessary updates and also have full control over when you consider a property changed.

新しい値が古い値と異なるかどうかのチェックは必須ではありませんが、推奨されます。そうすれば、不必要な更新を避けることができ、いつプロパティが変更されたと考えるかを完全に制御できます。

Table Of Contents

Previous topic

Implementing ArrayAccess for Domain Objects

ドメイン オブジェクトの ArrayAccess の実装

Next topic

Keeping your Modules independent

モジュールの独立性を保つ

This Page

Fork me on GitHub