Repository Design Pattern Implementation in Laravel — Using Laravository Package
What is Repository Design Pattern?
Repository Design Pattern is a kind of container where data access logic is stored. It hides the details of data access logic from business logic. In other words, we allow business logic to access the data object without having knowledge of the underlying data access architecture.
Why we should Repository Design Pattern?
The main idea to use Repository Pattern in a Laravel application is to create a bridge between models and controllers. In other words, to decouple the hard dependencies of models from the controllers. The model should not be responsible for communicating with or extracting data from the database.
And why Laravository package?
With this package, it allows us to create the Repository Class and the Interface in one line of command. So, we don't need to do the same thing repeatedly.
There are many approaches to implement Repository Design Pattern.
In this article, we will use a Laravel Package named Laravository.
Before we do the implementation, we need to setup our package.
First, install the Laravository to our laravel project from the composer. run this composer command.
composer require akunbeben/laravository
Then, we need to publish the Provider. run this artisan command below.
php artisan repository:provider
After the provider got published, we need to register
RepositoryServiceProviderclass to the
That’s it, our setup to implement design completed.
Now, we will do the implementation of
First, we can use the Laravository command to create the Repository Class and the Interface like this.
php artisan make:repository User
It will generate
UserRepositoryInterfaceThe Repository class would look like this.
Before we can use this
UserRepository . we need to register it to the RepositoryServiceProvider. Like this example below.
Now, finally. We can call the interface in our controller.
Maybe, you will ask me where does the
create method comes from?
So, The BaseRepository itself has default methods to do some default stuff. like Getting data, create data, update data, and delete data.
Here are lists of the default methods.