The objective of PHP traits is to manage a bunch of logic. However what is the best way to make this bunch of logic works according some dedicated attributes and avoiding naming conflicts ?
I'm thinking about MVC and particularly the model class. Indeed models seems to be good candidates for traits. Models can implement tree structure, be draftable, revisionnable, sluggable, and so on.
I would like to write something like this:
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 ? */
}
}
}
If I intend to set the Tree trait like this :
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...*/
}
I'll reach into naming conflicts because of $_defaults
since each trait needs its own defaults. Using the name of the trait as attribute name imply using something like (new ReflectionClass(__CLASS__))->getTraits())
... which is not really awesome.
In other words is there a way to create traits with "overridable defaults" and avoid naming conflicts ?