Don’t just create the Model, implement Repository Pattern

Think a scenario where your application uses MySQl database, and you need to switch to a different DB,that means are you going to rewrite your database logic again?. Thanks to Laravel Repository Pattern, which does that for you.
Since the Repository Pattern uses interfaces as contracts, your application logic will remain the same and all you have to do is change out the repository. Sounds easy, right? Let’s dive in with a simple example.

Lets create a model with a migration file

Let say we have few columns id, name and email

and run the migration as php artisan migrate and our table is ready.

Now Lets create two folders under app directory
1. Repositories
2. ServiceProvider

Create the Repository Interface

Create the Repository Class

Register our Repository with Laravel’s IoC Container
Create a new MySampleServiceProvider class which will extends the ServiceProvider

The last step is to add our custom provider in config/app.php as

Now it is ready to serve in our Controller. Let say we have a controller SampleController

in route.php add a route Route::get(‘/test’,’SampleController@test’); and browse http://yourUrl/test.You can see the result.

Let say if you want to switch to a different database, then just create another Repository Class, update the class in IOC container and you are good to go. So here you go

and Update the ServiceProvider class

About the author

Janaki( - A Software developer with 9+ years of experience in multiple technology projects across web, mobile, and cloud applications with expertise in PHP, C#, MySQL, Web services and open source platforms.

Similar Posts

Comments are closed.