创建Laravel存储库并绑定为服务提供者

问题描述 投票:3回答:1

我有一个Symfony和Spring背景,这是我与Laravel合作的第一个项目,据我了解,Laravel没有对存储库的内置支持。我找到了一些教程;他们中的一些人尝试提供像Spring或Symfony这样的体系结构。

例如,此博客suggests an folder structure像这样:

---- Repository
------ Eloquent
-------- UserRepository.php // extends BaseRepository
-------- BaseRepository.php // implements EloquentRepositoryInterface
------ UserRepositoryInterface.php
------ EloquentRepositoryInterface.php 

这还不错。我感到困惑的是,作者建议将这些存储库绑定为服务提供者,并在控制器中将它们作为提供者进行访问。

class RepositoryServiceProvider extends ServiceProvider 
{  
    public function register() 
    { 
        $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class);
        $this->app->bind(UserRepositoryInterface::class, UserRepository::class);
    }
}

我决定在Github中找到一个库,该库专注于创建Eloquent存储库,该库直接消耗了控制器中的User存储库:

class HomeController extends Controller
{
    public function index(UserRepository $userRepository)
    {
        return $userRepository->get();
        ...

从体系结构的角度来看,我们是否需要将存储库绑定为提供者? (让我们考虑一个事实,即AWS或Elastic Search可能会加入项目,并且存储库可能因单个模型而异)

而且最重要的是,为什么Laravel没有内置的存储库模式支持?谢谢

php laravel eloquent repository-pattern
1个回答
1
投票

为什么Laravel没有内置的存储库模式

因为对于完全使用它们应如何使用尚无共识。

例如,我使用存储库作为需要实例化模型实例的laravel模型和laravel控制器之间的中介,我从不将它们注入控制器中,而是在需要时手动实例化它们。

我们需要将存储库绑定为提供者吗?

如上所述,目前尚无共识,所以[[NO。

根据您设计存储库的方式,您可以手动实例化它们,将它们注入到控制器的实例化中(在__contruct(UserRepository $userRepository)中,如您从larcast的laravel教程中在laravel中看到的,或将它们用作服务提供者。

0
投票

来自Laravel Repository Pattern – How to use & why it matters

最后一步是在我们的config / app.php中注册该服务提供商。打开此文件,然后将我们的提供程序App \ Providers \ RepositoryServiceProvider :: class添加到提供程序中:>

现在,我们的应用程序知道当我们键入一个对象通过其接口。

这就是为什么您需要这样绑定接口的原因:

/** * Register services. * * @return void */ public function register() { $this->app->bind(EloquentRepositoryInterface::class, BaseRepository::class); $this->app->bind(UserRepositoryInterface::class, UserRepository::class); }

为了让Laravel知道在控制器中进行实例化时要实例化的内容:

private $userRepository; public function __construct(UserRepositoryInterface $userRepository) { $this->userRepository = $userRepository; }

© www.soinside.com 2019 - 2024. All rights reserved.