kamilwylegala / immutable-setter
PHP 的实用类,帮助您使类不可变。
0.1.1
2018-06-02 16:23 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 5.4.*
This package is not auto-updated.
Last update: 2024-09-29 23:47:52 UTC
README
一个小型实用类,通过添加 with 方法帮助您使类不可变。
灵感来自 Lombok 的 @Wither 注解。
它允许您轻松地添加 withX
方法,以克隆具有修改后一个属性的对象。
安装
使用 composer 从 packagist 获取库
$ php composer.phar require kamilwylegala/immutable-setter
用法
- 将
with
字段添加到您的类中。 - 将
new Wither($this, ["arg1", "arg2"])
分配给此字段,并提供具有适当参数顺序的构造函数模式。您也可以省略第二个参数,让Wither
自动解析构造函数参数。 - 向您的类中添加公共
withArg1
方法,并放置以下内容
return $this->wither->getInstance("arg1", $newArg1)
- 运行
$valueObject->withArg1($newArg1)
将创建一个对象副本,其$arg1
字段已更改。
示例
use KamilWylegala\ImmutableSetter\Wither; class Person { private $name; private $age; private $wither; public function __construct($name, $age) { $this->name = $name; $this->age = $age; $this->wither = new Wither($this, ["name", "age"]); //Second param is optional. } public function withName($newName) { return $this->wither->getInstance("name", $newName); } }
测试
安装开发依赖项并在根目录下运行
$ vendor/bin/phpunit
许可
MIT