PHP trait 的目标是管理一堆逻辑。但是,使这组逻辑根据一些专用属性工作并避免命名冲突的最佳方法是什么?
我在考虑 MVC,尤其是模型类。事实上,模型似乎是特征的良好候选者。模型可以实现树结构、可起草、可修订、可插入等。
我想写这样的东西:
class MyModel extends Model {
use Tree, Revision, Slug;
protected $_behaviors = array(
'Tree' => array('parentFieldname' => 'p_id'),
'Revision' => array(/* some options */),
'Slug' => array(/* some options */)
);
public function __construct() {
foreach($this->_behaviors as &$options) {
$options += /* trait defaults ? */
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我打算像这样设置 Tree 特性:
trait Tree {
protected $_defaults = array(
'parentFieldname' => 'parent_id',
/*...other options...*/
);
public function moveUp();
public function moveDown();
public function setParent(); //<- need the `'parentFieldname' => 'p_id'`attribute
/*...and so on...*/
}
Run Code Online (Sandbox Code Playgroud)
我将涉及命名冲突,$_defaults因为每个特征都需要自己的默认值。使用 trait 的名称作为属性名称意味着使用类似(new ReflectionClass(__CLASS__))->getTraits())... 的东西,这并不是真的很棒。
换句话说,有没有办法创建具有“可覆盖默认值”的特征并避免命名冲突?
就像您在每个 OOP 概念中所做的那样:睁开眼睛!这完全相同,因为您扩展了一个类并滥用了现有的属性。而已。
class A {
protected $defaults = array ('foo' => 'bar');
}
class B extends A {
protected $defaults = array('foo2' => 42); // Bum: 'foo' disappeared
}
Run Code Online (Sandbox Code Playgroud)
$_defaults无论如何,拥有一个通用的-property 听起来就像是一种代码气味:什么“默认值”?这是默认的?系统默认?应用程序默认值?[1] 用值来设置你的类,而不是“默认值”,因为那是(传播默认值)用于初始化过程的东西,或者具体属性的初始化(public $parentFieldName = 'parent_id';)
trait A {
public $parentFieldName = 'parent_id';
public function construct ($options) { /
if (isset($options['parentFieldName'])) {
$this->parentFieldName = $options['parentFieldName'];
}
}
}
class Foo {
use A {
A::construct as protected constructA;
}
public function __construct ($options) {
$this->constructA($options['A']);
}
}
Run Code Online (Sandbox Code Playgroud)
一些注意事项:重要的是,您使用别名construct()是因为它也会与其他方法(来自其他特征)发生冲突,并且construct()不是特殊方法。它只是以这种方式命名(来自我)来澄清,它是“一种”构造函数。其他类似init()或类似的名称当然也可以使用;) 您必须自己在“真正的”构造函数中调用它(请参阅Foo::__construct()参考资料)。
[1] 作为标识符的“默认”就像“类型”、“状态”、“i”……:它们是通用的,才有用。