The Repository Pattern can be very helpful khổng lồ you in order khổng lồ keep your code a little cleaner and more readable. In fact, you don’t have lớn be using Laravel in order lớn use this particular thiết kế pattern. For this episode however, we will use the object oriented php framework Laravel khổng lồ show how using repositories will make our controllers a bit less verbose, more loosely coupled, & easier to lớn read. Let’s jump in!

Working Without Repositories

Using repositories is not mandatory! You can accomplish many great things in your applications without using this pattern, however, over time you may be painting yourself into a corner. For example by choosing not khổng lồ use repositories, your application is not easily tested & swapping out implementations would be cumbersome. Let’s look at an example.

Bạn đang xem: Laravel repository pattern

Getting House Listings From a Real Estate Database


This would be pretty typical code for using Eloquent to interact with the database which holds listings of houses for sale. It will work just fine, but the controller is now tightly coupled lớn Eloquent. We can inject a repository instead to create a loosely coupled version of the same code. This loose coupling makes it easy khổng lồ swap implementations at a later time.

Working With Repositories

There are a fair number of steps khổng lồ complete the entire repository pattern, but once you go through it a few times it becomes second nature. We’re going lớn cover every step here.

1: Create the Repository Folder

We recently looked at a common Laravel file Structure you might be using. This creates a thư mục in the tiện ích directory to hold all of your domain name specific files. For this example we’ll create the repotutrepositories within our app thư mục to contain our files. This also sets up our namespace structure which we will need to keep in mind for the files we create.

2: Create Your Interface

The next step is to create the interface which will determine the contract our repository must implement. This just lays out the methods that must be present in our repository. Our Interface will look like the following. Cảnh báo the namespace và methods we will use.


3: Create Your Repository

We can now create the repository which will vày all of the heavy lifting for us. It is in this file that we can put all of our detailed Eloquent queries, no matter how complex they may become. Each method simply has a custom name so that in our controller, we can just write some very short code to lớn get the desired result. Again chú ý the namespace và the use House; statement.


4: Create Backend Service Provider

For our controller, we are going khổng lồ type hint an interface. We are going to lớn be doing dependency injection, but by way of an interface essentially. What this means is that we need lớn register the interface with Laravel so that it knows which implementation of our interface we want to lớn use. We’ll first use an Eloquent implementation, but later we’ll move to lớn a file based implementation to lớn show how we can swap implementations easily using an interface. We place this Service Provider in the same namespace as our other files so far.


app->bind('repotutrepositoriesHouseRepositoryInterface', 'repotutrepositoriesDbHouseRepository');}}This code basically says, when you see the controller type hinting HouseRepositoryInterface, we know you want khổng lồ make use of the DbHouseRepository.

5: Update Your Providers Array

Now that we have created a new Service Provider, we need to địa chỉ cửa hàng this khổng lồ the providers array within app/config/app.php. It may look something like this once complete:

'providers' => array('IlluminateFoundationProvidersArtisanServiceProvider','IlluminateAuthAuthServiceProvider','IlluminateCacheCacheServiceProvider','IlluminateSessionCommandsServiceProvider','IlluminateFoundationProvidersConsoleSupportServiceProvider','IlluminateRoutingControllerServiceProvider','IlluminateCookieCookieServiceProvider','IlluminateDatabaseDatabaseServiceProvider','IlluminateEncryptionEncryptionServiceProvider','IlluminateFilesystemFilesystemServiceProvider','IlluminateHashingHashServiceProvider','IlluminateHtmlHtmlServiceProvider','IlluminateLogLogServiceProvider','IlluminateMailMailServiceProvider','IlluminateDatabaseMigrationServiceProvider','IlluminatePaginationPaginationServiceProvider','IlluminateQueueQueueServiceProvider','IlluminateRedisRedisServiceProvider','IlluminateRemoteRemoteServiceProvider','IlluminateAuthRemindersReminderServiceProvider','IlluminateDatabaseSeedServiceProvider','IlluminateSessionSessionServiceProvider','IlluminateTranslationTranslationServiceProvider','IlluminateValidationValidationServiceProvider','IlluminateViewViewServiceProvider','IlluminateWorkbenchWorkbenchServiceProvider','repotutrepositoriesBackendServiceProvider'),

6: Update Your Controller for Dependency Injection

We have most of the groundwork in place. We can now update the Controller khổng lồ facilitate injecting an implementation of the HouseRepositoryInterface. This will all us khổng lồ remove any calls khổng lồ Eloquent directly in the Controller, and replace those with simple custom method calls. Our updated controller might look something lượt thích this:


house = $house;}public function index()$houses = $this->house->selectAll();return View::make('houses.index', compact('houses'));public function create()return View::make('houses.create');public function show($id)$house = $this->house->find($id);return View::make('', compact('house'));}

7: Confirm Routes are Correct

For this example we simply phối up a route resource lượt thích so:

8: Update composer.json

If you have not done so already, make sure that the namespace we are referencing is in your composer.json. Note the addition of "psr-4":"repotut": "app/repotut" which tells composer lớn autoload the classes within the repotut namespace.

"name": "laravel/laravel","description": "The Laravel Framework.","keywords": <"framework", "laravel">,"license": "MIT","require": "laravel/framework": "4.2.*","autoload": "classmap": <"app/commands","app/controllers","app/models","app/database/migrations","app/database/seeds","app/tests/TestCase.php">, "psr-4": "repotut": "app/repotut" ,"scripts": "post-install-cmd": <"php artisan clear-compiled","php artisan optimize">,"post-update-cmd": <"php artisan clear-compiled","php artisan optimize">,"post-create-project-cmd": <"php artisan key:generate">,"config": "preferred-install": "dist","minimum-stability": "stable"Don’t forget lớn run composer dump after updating composer.json!Whoa! Nice work partner, let’s demo it in the browser. We can visit http://localhost/repotut/public/houses and we can see that we have 3 houses for sale, each a different color.


Easy to lớn Change Implementations

Let’s say in the future you decide that Eloquent is not the way you want to handle storing data with your app. No problem! Since you already laid out the ground work for using an interface, you can simple create a new repository & change the Service Provider. Let’s see how we can swap implementations.

1: Create a New Repository

We’ll just use a quick example here. Let’s pretend this is a whole file system class which provides data storage via flat files. In our case, we’ll just put some simple xúc tích và ngắn gọn in to demo swapping implementations. Note that this class implements the same exact methods as the Eloquent version we tested prior.


color = 'Olive';$house2 = new stdClass;$house2->color = 'Yellow';$house3 = new stdClass;$house3->color = 'Brown';$houses = array($house1,$house2,$house3);return $houses;}public function find($id)return 'Here is a single house listing, again using the tệp tin system';}

2: Update Service Provider

Now in the Service Provider, all we have to do is change one single line of code! We simply tell Laravel that now when you see the HouseRepositoryInterface, you will use the FileHouseRepository instead of the DbHouseRepository.

Xem thêm: Cái Dĩa Tiếng Anh Là Gì ? Cái Dĩa In English Translation

app->bind('repotutrepositoriesHouseRepositoryInterface', 'repotutrepositoriesFileHouseRepository');}}When we demo it in the browser at http://localhost/repotut/public/houses we can see that the new implementation has indeed taken effect, very cool!


Repositories Conclusion

As you can see, it seems like a lot of steps khổng lồ get Repositories working in your application. There are a few steps involved, no doubt about it. If you are going lớn be responsible for maintaining a piece of code for the long term however, you are going lớn reap the benefits of taking the time to correctly architect your phầm mềm in the beginning. Consider it a khung of delayed gratification, which in this day & age seems lượt thích a forgotten art.