Introducing the Repository Pattern in Laravel

Tram Ho

Repository Pattern is an optimal design that helps you optimize, save code, and reuse in many places. In Laravel, it is between Model and Controller. This is where the data queries are executed. In the past you would usually write into controllor but you feel like you are iterating pretty much, especially the CRUD functions, almost every controller is quite similar. In this article, I will introduce to you the Repository to reduce code duplication in Controllers.

Question

If you have 2 controllers, Post and Category to have features to add, delete, edit … in these features, you just need to modify the Model, it is the same. So, you can completely deploy the Repository for it as follows

Deploy Repository

First, you create the Repositories folder on par with the app in your Laravel project. Inside I create an Eloquent folder (to contain Post and Category) and two files are EloquentInterface.php and EloquentRepository.php.

Inside EloquentInterface.php

Inside EloquentRepository.php

In EloquentRepository.php will have variable $ model received from the Repository model infused after the override method Eloquent getModel Inside the folder created above, I created another file is next 2 CategoryRepository.php and PostRepository.php

Content in CategoryRepository.php

I simply overwrite the getModel function and pass it to the Model Category

Similarly, below is the PostRepository which will look like this:

How to use the created repositories

First, you need to go to AppServiceProvider.php as shown below and pass the register function code below

So you have successfully declared the Repository, in the next step, you go to the Controller to use the created Repository. My example is CategoryController (you need to create CategoryController)

  • Declare use App Repositories Model CategoryRepository; You add construct as below.

Or to create a new category, you can call it as shown below

In PostController you can do the same as on CategoryController.

Conclusion

The Repository Pattern is really effective and helps programmers a lot in reducing code repetition and being tighter in code lines. Hopefully, through this article, you can deploy Repository in your laravel project. If you have any questions, please comment below for me to discuss. Thank you for reading this article!

Share the news now

Source : Viblo