Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Repositories

Tags:

What are the advantages of Repositories in Laravel? It seems to be abstracting the Model layer from the business logic of the application. Although it really just seems to make the whole request life cycle just that much more complicated for little gain.

Can someone shed light on the advantage of Laravel repositories?


Edit

After now using repositories for some time I would add the following:

  • Repositories enforce single responsibility
  • Repositories should only return one collection of entities
  • Although separate from dependancy injection the concepts are brothers
  • Storage abstraction for the actual storage implementation (e.g. MySQL)
  • Easier testing
like image 416
AndrewMcLagan Avatar asked Jun 28 '13 14:06

AndrewMcLagan


2 Answers

Repositories, like in the provided tutorial, aren't necessary a Laravel concept. Rather, they're a form of IoC injection that is possible with Laravel. Any object that might similarly be injected doesn't mean it's a repository. See the video for a good example from Taylor Otwell, which happens to use a "repository" as well: http://vimeo.com/53029232.

In this example, the repository abstracts where the data came from that is passed to the controller. As long as the data passed implements the specified interface, the controller can "blissfully" make use of the interface's defined methods without worry about where the data initially came from. This allows switching the initial source of the data without breaking your controller. You could pull the data from a file, a database, an outside API, a mock object, or just some arbitrary array. Basically, the controller doesn't need to gather the data represented by the repository. It can just receive and use.

like image 101
kfriend Avatar answered Oct 08 '22 00:10

kfriend


In addition to the other answers here, it's worth pointing out that repositories used when used in Laravel can add an extra level of expressiveness. Take for example the following:

$users = User::whereHas("role", function($q) {     $q->where('name', 'moderator'); }, '<', 1)->get(); 

The code is difficult to read and awkward to look at. It can be encapsulated in a repository method, and demonstrate much clearer code intent:

$users = $userRepository->getUsersWhoAreNotModerators(); 

This is also achievable using eloquent 'query scopes' but I think using a repository is superior, as is adheres much better to the single responsibility principal, and is doable regardless of whether you are using Eloquent.

like image 39
James Flight Avatar answered Oct 08 '22 00:10

James Flight