Repository Design Pattern
Introduction#
The repository paatern is one of the most powerful patterns for handling data either in storing, deleting or fetching data from database.
In Mongez, the repository provides a simple way to handle advanced and complex usage when dealing with data.
In theory, the repsotiroy design pattern mainly works with models to handle data from and to database, as it is used as an additional layer between top layers like controllers and models.
Repository Structure#
Each repository MUST implement HZ\Illuminate\Mongez\Contracts\Repositories\RepositoryInterface which contains the following methods:
Thankfully, Mongez is shipped with Repository Managers that handles most of the prior methods with robust features to organize your operations.
Repository Initiation#
Repositories declartions are stored on the Mongez Configurations Repositories Section, each repository has an alias for quicker usage instead of injecting the repository class.
tip
All repositories are singletons, which means when you call any repository from anywhere, it will create only single instance of it.
Using Repositories#
Repositories can be called with 5 ways
1. Using Service Containers#
Repositories can be injected into any method using Laravel Service Container or IoC.
info
This is not the prefered way to use repositories, it can be used though.
2. Using repo function#
The repo(string $repositoryAlais): RepositoryInterface can be used from anywhere in the application.
3. Using ApiController#
Any controller extends ApiController class, a REPOSITORY_NAME constanct can be declared in the derived class with the repository alias name, then from any method the repository property can be used as a reference to the repository instance.
tip
This is the recommended way if you're extending any Mongez Base Controller for using repositories.
3. Using AdminApiController#
Similar to the ApiController except that the repository name is in the controller options array.
5. Using Repositry Trait#
Another way of using repositories is by using Repository Trait.
This will allow you to use any repository from the class that injects the repositry trait.
Generating new repository#
To create a new repository, use the following command line:
This will create a new repository classes located in the Users module Repositories directory.
Repository Simpler Structure#
All inherited repositories from any Repository Maanger have mere constants and methods for quicker development.