codelicia / immutable
此包已被弃用且不再维护。未建议替代包。
强制任何PHP对象的初始化属性不可变
dev-master
2021-07-22 09:48 UTC
Requires
- php: ^7.4
Requires (Dev)
- phpunit/phpunit: ^7.5.0
This package is not auto-updated.
Last update: 2021-08-04 00:10:38 UTC
README
由于PHP RFC: Readonly properties 2.0将在PHP 8.1中可用,因此此存储库将被存档。
它强制初始化属性不可变。
不可变属性可以非常有用,可以避免getter/setter
样板代码,或者只是强制特定对象不可变。
我们认为它在以下用例中特别有用:VOs、DTOs、Commands、Events和ViewModels。
安装
$ 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; } }
作者
- Jefersson Nathan (@malukenho)