我有几个共享一些共同功能的模型(由于它们的多态性),我想将它们引入ResourceContentModel类(甚至是特征).
ResourceContentModel类将扩展雄辩的Model类,然后我的各个模型将扩展ResourceContentModel.
我的问题是围绕模型字段,如$with,$appends和$touches.如果我将这些用于ResourceContentModel中的任何常用功能,那么当我在我的子模型类中重新定义它们时,它会覆盖我在父类中设置的值.
寻找一些干净利落的建议吗?
例如:
class ResourceContentModel extends Model
{
protected $with = ['resource']
protected $appends = ['visibility']
public function resource()
{
return $this->morphOne(Resource::class, 'content');
}
public function getVisibilityAttribute()
{
return $this->resource->getPermissionScope(Permission::RESOURCE_VIEW);
}
}
class Photo extends ResourceContentModel
{
protected $with = ['someRelationship']
protected $appends = ['some_other_property']
THESE ARE A PROBLEM AS I LOSE THE VALUES IN ResourceContentModel
}
我正在采取一种干净的方式来做到这一点,因为我已经在层次结构中的额外类中插入以收集公共代码的事实不会过度改变子类.
最佳答案 不知道这是否有效……
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::$this->with);
}
}
或者也许在ResourceContentModel上添加一个方法来访问该属性.
class ResourceContentModel extends Model
{
public function getParentWith()
{
return $this->with;
}
}
然后
class Photo extends ResourceContentModel
{
public function __construct($attributes = [])
{
parent::__construct($attributes);
$this->with = array_merge(['someRelationship'], parent::getParentWith());
}
}
编辑
在第3个片段的构造函数中,
$this-> with = array_merge([‘someRelationship’],parent-> getParentWith());
需要
$this-> with = array_merge([‘someRelationship’],parent :: getParentWith());