codelicia/immutable

此包已被弃用且不再维护。未建议替代包。

强制任何PHP对象的初始化属性不可变

安装: 0

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 5

分支: 0

开放问题: 3

类型:项目

dev-master 2021-07-22 09:48 UTC

This package is not auto-updated.

Last update: 2021-08-04 00:10:38 UTC


README

Build Status

由于PHP RFC: Readonly properties 2.0将在PHP 8.1中可用,因此此存储库将被存档。

它强制初始化属性不可变。

不可变属性可以非常有用,可以避免getter/setter样板代码,或者只是强制特定对象不可变。

我们认为它在以下用例中特别有用:VOsDTOsCommandsEventsViewModels

安装

$ composer require codelicia/immutable

使用

只需将ImmutableProperties特质添加到类中即可在类上启用不可变性。

final class User
{
    use \Codelicia\ImmutableProperties;

    public string $name;
    public int $age;
}

$user       = new User;
$user->name = "@malukenho";

// this will crash
$user->name = "Throws exception as the property name cannot be reassigned";

我们建议您创建一个__construct,以确保对象在实例化后立即处于有效状态,但这取决于您和您的需求。

final class User
{
    use \Codelicia\ImmutableProperties;

    // It is fine to leave the properties visibility as public as the `ImmutableProperties`
    // trait will not allow it to change after it is being initialized in the
    // class constructor
    public string $name;
    public int $age;

    public function __construct(string $name, int $age)
    {
        $this->init(); // The `init()` method must be called here

        $this->name = $name;
        $this->age = $age;
    }
}

作者