brunnofoggia / darktrait
1.6.0
2017-09-01 16:56 UTC
Requires
- php: >=5.4.0
README
一组必要的工具,使特质成为现实
默认值属性在特质上默认情况下,PHP不允许你在特质上扩展属性,除非解决冲突。使用DarkTrait,您将能够设置一个属性列表及其默认值,并且使用您的类的属性将能够设置自定义值
通过键名全局属性此功能允许在实体之间共享一个值,作为静态属性不幸的是,特质不能有静态属性,所以当你处于特质的第二层,需要全局值,当类是主题,在第一层时,你不能原生地拥有它。
默认属性的使用
在您的类中添加以下代码
use \DarkTrait;
按如下所示设置您的属性列表属性
protected $attrDefaults = [ 'test_property' => '1', ];
在需要自定义它们的类中设置属性
protected $test_property = '2';
使用此方法捕获属性值
$this->getAttr('test_property');
使用此方法设置属性值
$this->setAttr('test_property', 'some value');
静态属性的使用
在第一层的特质中设置默认attrDefaults[DarkTraitGlobal],使用键值(名称即可)
protected $attrDefaults = [ 'DarkTraitGlobal' => 'MyTraitName', ];
使用getGlobal和setGlobal来完成魔法
$this->getGlobal('some_key'); // in Classes world would be like MyClass::$some_key $this->setGlobal('some_key', true); // will set true as some_key value
高级使用
您可以通过设置(这将对实际属性名称产生影响,而不是在'attrDefaults'中存在的键)来自定义属性名称,使其具有前缀或后缀
protected function formatAttrName($name) { return 'my_'.$name; }
可以为每个属性创建一个getter/setter。以下示例中创建了一个名为'layout'的属性getter
protected function getAttr_layout() { ... } protected function setAttr_layout($value) { ... }
想要更改数组列表属性中的某些更改。也许将属性设置到您的实例中会有所帮助
$this->explicitAttr($name);
想要从文件中导入默认属性值列表吗?使用此方法
$this->setAttrList($array);
如果您已经为另一个需求声明了'attrDefaults'属性,您可以将其重命名为任何其他名称
protected function getAttrProperty() { return isset($this->otherAttrDefaults) ? $this->otherAttrDefaults : []; }
当使用两个使用DarkTrait的特质时解决冲突,通过组合它们的默认属性列表
// 1st you need to define which one of the two traits methods will be the one assuming the front, just to solve the conflict \TraitOne::formatAttrName insteadof \TraitTwo; \TraitOne::getAttr insteadof \TraitTwo; \TraitOne::getAttrMethod insteadof \TraitTwo; \TraitOne::setAttrList insteadof \TraitTwo; // 2nd you will rename everything that conflicted between them \TraitOne::formatAttrName as TO_formatAttrName; \TraitOne::getAttr as TO_getAttr; \TraitOne::getAttrMethod as TO_getAttr; \TraitOne::getAttrProperty as TO_getAttrProperty; \TraitTwo::formatAttrName as TT_formatAttrName; \TraitTwo::getAttr as TT_getAttr; \TraitTwo::getAttrMethod as TT_getAttr; \TraitTwo::getAttrProperty as TT_getAttrProperty; // 3rd specify getAttrProperty to combine their attributes and yours (if you have the attributes default list too) public function getAttrProperty() { // use the code bellow if you do not have a list of default attributes $data = array_merge_recursive($this->TO_getAttrProperty(), $this->TT_getAttrProperty()); // or this one if you do have a list of default attributes $data = array_merge_recursive($this->TO_getAttrProperty(), $this->TT_getAttrProperty(), $this->attrDefaults); return $data;
}