2015-04-05 55 views
1

我正在使用最近的存储库,我试图解决一些默认操作或主要存储库中名为AbstractRepository的行为。使用Laravel容器作为存储库

AbstractRepository看起来是这样的:

class AbstractRepository 
{ 
    protected $session; 
    protected $loggedUser; 

    public function __construct(Session $session) 
    { 
    $this->session = $session->current(); 
    $this->loggedUser = $session->currentUser(); 
    } 
} 

在每一个存储库我希望能够利用这些特性,但我必须调用parent::__construct()在每一个存储库来执行的构造。

有什么办法可以让laravel的容器处理这个,而不是调用每个存储库中的父构造函数吗?

所以我可以做这样的:

class CommentRepository extends AbstractRepository implements ICommentRepository 
{ 
    public function like($commentId) 
    { 
    $entry = Like::where('comment_id', $commentId)->where('user_id', $this->loggedUser->id); 
    } 
} 

回答

0

如果扩展另一个(抽象)类没有重载父构造父类的构造函数的类将被自动调用。

所以,如果你有这样的事情:

class CommentRepository extends AbstractRepository implements ICommentRepository 
{ 
    public function __construct(Session $session){ 
     $this->foo = 'bar'; 
    } 
} 

你将不得不增加parent::__construct()如果你想构造中AbstractRespository被调用。

public function __construct(Session $session){ 
    parent::__construct($session); 
    $this->foo = 'bar'; 
} 

但是,如果你的构造方法看起来就像这样,你完全可以将其删除:

public function __construct(Session $session){ 
    parent::__construct($session); 
}