spaark / composite-utils
此包已被废弃,不再维护。未建议替代包。
复合对象模型工具
v1.1.0
2017-03-11 02:05 UTC
Requires
- php: >=7.1
Requires (Dev)
- phpunit/phpunit: ^6.0
This package is not auto-updated.
Last update: 2022-03-06 13:56:09 UTC
README
一组工具,使得与复合对象交互变得更容易
问题
复合对象通常只是具有有意义名称的属性集合。虽然这确实比仅仅使用数组要好,但这通常需要一组长的getter和setter;这些方法往往只是移动值而已
public function setProperty($value) { $this->property = $value; } public function getProperty() { return $this->property; }
冗余,冗余,还是冗余!
这是九行代码来重新实现仅仅是 $object->property = $value
的事情。最多,这些行可能会强制某种形式的数据类型值
public function setProperty(RequiredPropertyType $value) { $this->property = $value; }
这个问题也存在于构造函数中,你有多经常看到类似这样
public function __construct($value1, $value2, $value3, $value4, $value5) { // Set values $this->value1 = $value1; $this->value2 = $value2; $this->value3 = $value3; $this->value4 = $value4; $this->value5 = $value5; // Init Values $this->value6 = new Collection(); $this->value7 = new HashMap(); }
解决方案
这个库引入了一套工具,可以去除复合getter、setter和膨胀的构造函数的需要,同时不放弃对属性访问和数据类型强制控制的控制。
class MyAwesomeComposite { use AutoConstructTrait; use PropertyAccessTrait; /** * @var int */ protected $property = 42; /** * @var string * @readable * @writable */ protected $stringProperty = 'some value'; /** * @var DataType * @readable * @construct required */ protected $iNeedThis; /** * @var ArrayObject * @readable * @construct new */ protected $collection; }
就是这样。不再需要其他任何东西!所有除了 $property
以外的属性在需要时都可以访问,并且 $collection
将自动为你构建。虽然你看不到,这个实体也包含一个需要...你猜对了... $iNeedThis
属性的构造函数,它需要一个 DataType
。如果传递给它的不是字符串,$stringProperty
也可以写入,如果可能,它将被自动转换成一个字符串
$class = new MyAwesomeComposite(); // Fails, $iNeedThis is required $iNeedThis = new OtherDataType(); $class = new MyAwesomeComposite(); // Fails, $iNeedThis should be a DataType $iNeedThis = new DataType(); $class = new MyAwesomeComposite($iNeedThis); // All good! var_dump($class->property); // Fails, not readable var_dump($class->stringProperty); // string(10) "some value" $class->stringProperty = 00000000123; var_dump($class->stringProperty); // string(3) "123" $class->iNeedThis = new DataType(); // Fails, not writable var_dump($class->collection); // ArrayObject { } var_dump($class->iNeedThis === $iNeedThis); // true