Creating Laravel repositories and binding as service providers

tolga :

I have a Symfony and Spring background, this is my first project with Laravel and as far as I understood Laravel doesn't have a build-in support for repositories. I found several tutorials; some of them try to offer architecture like Spring or Symfony.

As an example this blog suggests an folder structure like this:

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

which is not bad. The point I'm confused is, the author suggests to bind these repositories as service providers and access them in controller as providers.

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

Than I decided to find a library in Github which focuses on creating an Eloquent Repository, which directly consumes User repository in controller:

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

From architectural perspective, do we need to bind repositories as providers? (Let's think the fact that AWS or Elastic Search may join the project and repositories may vary for a single model)

And most importantly why doesn't Laravel have a built-in repository pattern support? Thank you

N69S :

why doesn't Laravel have a built-in repository pattern

Because there is no consensus on how they should be used if used at all.

For example, I use Repositories as an intermediary between laravel models and laravel controllers that needs the model instance to be instantiated and I never inject them into controllers but instantiate them manually when needed.

do we need to bind repositories as providers ?

As said above, there is no consensus so NO.

Depends on how you design your repositories, you can instantiate them manually, inject them into controller's instantiation (in the __contruct(UserRepository $userRepository)) as you can see in laravel from scratch tutorial from laracast or use them as service providers.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=9668&siteId=1