2017-06-17 45 views
3

我有幾個模型共享一些共同的功能(由於它們的多態性),我想將其拉入ResourceContentModel類(甚至是特徵)。

ResourceContentModel類將擴展雄辯的Model類,然後我的各個模型將擴展ResourceContentModel。

我的問題是圍繞像$,$ 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 
} 

一個乾淨的方式後,我要做到這一點這樣子類都不會過分的事實,我放進了一個額外的類層次結構中收集的改變通用代碼。

回答

1

不知道這是否會工作...

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()); 
    } 
} 

EDIT

在第三代碼段的構造,

$this->with = array_merge(['someRelationship'], parent->getParentWith());

需要個

$this->with = array_merge(['someRelationship'], parent::getParentWith());

+0

謝謝,我喜歡這個,我用你的第一個想法存在,但我把自定義的構造函數中ResourceContentModel類,而這意味着在子類可能都只是設置$帶和$附加正常人一樣。受保護而不是私有字段,可以在基類中訪問被覆蓋的值,以便我們可以將它們與常見值合併。不錯,整潔...... – madz

+0

很好聽,打出'parent :: $ this-> with'只是顯得很奇怪。但我很高興它的工作,可能不得不使用它有一天我自己=) – btl

+0

是不確定的特定語法(我不知道你可以做到這一點),但因爲我把你的建議的邏輯在父類的構造函數,我可以只參考$這個 - >與 – madz