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

tol*_*lga 5 php repository-pattern laravel eloquent

我有 Symfony 和 Spring 背景,这是我与 Laravel 的第一个项目,据我所知,Laravel 没有对存储库的内置支持。我找到了几个教程;他们中的一些人试图提供像 Spring 或 Symfony 这样的架构。

作为一个例子,这个博客建议了一个这样的文件夹结构

---- Repository
------ Eloquent
-------- UserRepository.php // extends BaseRepository
-------- BaseRepository.php // implements EloquentRepositoryInterface
------ UserRepositoryInterface.php
------ EloquentRepositoryInterface.php 
Run Code Online (Sandbox Code Playgroud)

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

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

比我决定在 Github 中找到一个库,它专注于创建一个 Eloquent 存储库,它直接使用控制器中的用户存储库:

class HomeController extends Controller
{
    public function index(UserRepository $userRepository)
    {
        return $userRepository->get();
        ...
Run Code Online (Sandbox Code Playgroud)

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

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

N69*_*69S 2

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

因为对于如果要使用它们应该如何使用还没有达成共识。

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

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

如上所述,没有达成共识,所以

取决于您设计存储库的方式,您可以手动实例化它们,将它们注入到控制器的实例化中(在 中__contruct(UserRepository $userRepository)),正如您在 laracast 的 laravel from scrap 教程中看到的那样,或者将它们用作服务提供者。