使用Laravel容器作为存储库

时间:2015-04-05 19:00:40

标签: php laravel containers ioc-container laravel-5

我最近使用了存储库,并且我尝试在主存储库中解决一些名为AbstractRepository的默认操作或所需行为。

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

1 个答案:

答案 0 :(得分: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);
}
相关问题