jasny/immutable

不可变对象的辅助方法

v2.1.0 2020-01-27 09:41 UTC

This package is auto-updated.

Last update: 2024-09-14 15:47:42 UTC


README

Build Status Scrutinizer Code Quality Code Coverage Packagist Stable Version Packagist License

该库提供了不可变对象的辅助方法。

安装

composer require jasny/immutable

使用

NoDynamicProperties

Jasny\Immutable\NoDynamicProperties 定义了 __set 方法,当尝试设置一个不存在的属性时,将抛出 LogicException

class ImmutableFoo
{
    use Jasny\Immutable\NoDynamicProperties;
}

With

不可变对象可能有 with... 方法,这些方法创建对象的一个修改版,而不可变对象本身保持不变。例如,PSR-7 中描述的类就是这样工作的:PSR-7

这些对象中的 with... 方法通常遵循相同的方法。

class ImmutableFoo
{
    public function withSomething(string $newValue)
    {
        if ($this->something === $newValue) {
            return $this;
        }

        $clone = clone $this;
        $clone->something = $newValue;

        return $clone;
    }
}

Jasny\Immutable\With 特质实现了受保护的 withProperty()withoutProperty() 方法,用于在对象的克隆上设置和取消设置属性。

class ImmutableFoo
{
    use Jasny\Immutable\With;
    
    protected $something;

    public function withSomething(string $value): self
    {
        return $this->withProperty('something', $value);
    }

    public function withoutSomething(): self
    {
        return $this->withoutProperty('something');
    }
}

特质包含 withPropertyKey()withoutPropertyKey() 方法,用于设置和取消设置关联数组的项。

class ImmutableFoo
{
    use Jasny\Immutable\With;

    protected array $colors = [];

    public function withColor(string $color, int $level): self
    {
        return $this->withPropertyKey('colors', $color, $level);
    }

    public function withoutColor(string $color): self
    {
        return $this->withoutPropertyKey('colors', $color);
    }
}

withPropertyItem()withoutPropertyItem() 方法用于对顺序数组进行操作,以添加和删除项。

class ImmutableFoo
{
    use Jasny\Immutable\With;

    protected array $services = [];

    public function withAddedService($service): self
    {
        return $this->withPropertyItem('services', $service, true /* unique */);
    }

    public function withoutService($service): self
    {
        return $this->withoutPropertyItem('services', $service);
    }
}

如果 withPropertyItem() 的第三个参数设置为 true,则如果该项已在数组中,则不会添加该项。

如果该项在数组中出现多次,则 withoutPropertyItem() 将删除所有这些项。使用严格比较来查找项。