php-libs/observable

提供类以简化观察者模式实现

1.3 2021-05-19 07:15 UTC

This package is auto-updated.

Last update: 2024-09-19 14:17:01 UTC


README

此包包含一组简单的类,以简化向属性方法添加观察者的过程。

特性

  • 在值更改之前执行 callable

  • 在特定值更改之前执行 callable

  • 在值更改之后执行 callable

  • 在特定值更改之后执行 callable

快速入门

安装

composer require php-libs/observable

示例:不带观察者属性的类

class MyClass
{
    private ?string $propertyA = null;

    private ?string $propertyB = null;

    public function setPropertyA(string $value)
    {
        $this->propertyA = $value;
    }

    public function setPropertyB(string $value)
    {
        $this->propertyB = $value;
    }
}

示例:带有观察者属性的类

class MyClass implements \PhpLibs\Observable\BeforeValueChangeObservableInterface
{
    private const PROPERTY_A = 'propertyA';
    private const PROPERTY_B = 'propertyB';
    
    use PhpLibs\Observable\BeforeValueChangeObservableTrait;
    use PhpLibs\Observable\AfterValueChangeObservableTrait;

    private ?string $propertyA = null;

    private ?string $propertyB = null;

    public function setPropertyA(string $value)
    {
        $this->raiseBeforeValueChange(static::PROPERTY_A, $this->propertyA, $value);
        $this->propertyA = $value;
        $this->raiseAfterValueChange(static::PROPERTY_A, $this->propertyA);
    }

    public function setPropertyB(string $value)
    {
        $this->raiseBeforeValueChange(static::PROPERTY_B, $this->propertyB, $value);
        $this->propertyB = $value;
        $this->raiseAfterValueChange(static::PROPERTY_B, $this->propertyB);
    }
}

完整示例

请参阅 example.php

输出如下

propertyA WILL CHANGE from "" to "A-1"
propertyB WILL CHANGE from "" to "B-1"
Begin observing After B Changed
propertyA WILL CHANGE from "A-1" to "A-2"
propertyB WILL CHANGE from "B-1" to "B-2"
propertyB CHANGED to "B-2"
End observing After B Changed
propertyA WILL CHANGE from "A-2" to "A-3"
propertyB WILL CHANGE from "B-2" to "B-3"