Introduction
We created a open source package with our implimentation of the repository pattern. This gives you alot of boiler plate to write less code. You will need to be diciplined to use the functions correctly and stick with your standards.
This keeps your controllers lean and moves your domain logic to the servcie classes, with your database logic / queries to the repository classes. For instance you add a register method in your UserService and you can use the same logic to register a user from a controller, command, job etc which linkes back to the DRY principle.
Best practices is to create a repository class for each model and you can import all the repositories classes you need into the services. Service classes should also not be very long classes if there are more than 10 methods in a class maybe create a seperate class. (This is all up to the developer, if the functions is related to the class keep them together.)
You should NOT query models directly in your code, queries should be done in the repositories.
Repository Pattern
From the pacakge you can see that the folder structure for the pattern we used standard location for Laravel to add extra functionality. Repositories will be added in the base directory of \App\Repositories and services will be added in the base directory of \App\Services. You are obviously free to change the directories in the config file of the pacakge.
Create Service class
php artisan base:create Users/User -s
This will create the UserServices class in the Services directory \App\Services\Users\UserService
Create Repository class
php artisan base:create Users/User -r --model=App/Models/Users/User
This command will create the repository files in \App\Repositories\Users\UserRepository\Interface\UserRepositoryInterface & \App\Repositories\Users\UserRepository.
Specifying the model in this command will automatically link the relevant model class to the repository, the model will automatically be injected in the construct method of the class. Each model class will needs its own repository files, this linkes back to Single responsabiulity principle to keep classes having a single responsability.
Create Service & Repository class at the same time.
php artisan base:create Users/User -s -r --model=App/Models/Users/User
This will automatically create a RepositoryProvider::class and link it to Laravel to register the repositories and interfaces together.
These custom repository classes automatically extend the BaseRepository classes so that you have access to prebuilt functions like create, update, delete, firstOrCreate, all, find, findBy, findOneBy etc, this is very usefull and reduces the amount of code you need to write for basic functions you preform on most models.
