Rules for Repository pattern

Controllers

Controllers need to BE THIN / LEAN.

The job of the controller is to receive the data from the request and return a response. All intervening logic should be delegated to a service method.

Services

The service method should have well-defined inputs and return types.

This way the same service method could be used not only by a controller but by a console task or an automated test.

The service method will call Repository methods to read data and Actions to write data.

Models

The Models should be used to control table names, writable fields and entity relationships. Querying and returning actual data should be the responsibility of a repository.

If the Models get too fat, responsibilities belonging to one Model can easily leak into code in another Model, making code organisation difficult. An Eloquent Model should be responsible only for a single table.

Repositories

Even though this is Laravel with Eloquent, we find it helpful to use the repository pattern from Symfony.

A repository can be responsible for reading data connected to multiple tables.

By abstracting repositories away from Eloquent Models, we can keep the Eloquent Model clean but still express complex relationships between tables in an organised way.

Actions

Any operation that has a side-effect (writing data, writing files, sending notifications) should be delegated to an Action.

Actions implement the Action interface (ensuring that they have do() method).

This is to distinguish them from calculations and data. A calculation should be implemented as a pure function (ie its return value depends only on its arguments and it has no effect on state).

Comments in the code

Use the comments in the classes and methods where there is complex logic Example:

/**

What is the below code supposed to do

1. get the user_id from the authentication string

2. find the user details from the user profile

etc ... */

Last updated