How to Implement Repository Pattern in PHP

Intermediate

2019-03-23

What is Repository Pattern ?

Repository Pattern is an abstraction layer between the application business logic and persistence ( database ) layer.

In a three layer architecture. the application is divided into three main layers.

  • The Application Layer
  • The Service Layer
  • The Repository Layer

The Application Layer

  • It's the layer responsible for passing user's input.
  • Does some basic validations that are not related to the business.
  • A linkage layer between multiple services

The Service Layer

  • It's thee layer that contains the business rules and logic.
  • Do interactions with other services and network calls.

The Repository Layer

Also called Data Access Layer. It's responsible for dealing with database and data persistence. By providing a common repository interface that each provider can implement.

For example : SQL provider that uses SQL database to store the data and an XML provider that deals with the data in an XML format.

In this case we will have a common IRepository Interface that defines the common and basic CRUD operations.

Each concrete repository provider will implement the repository functions .

In MVC Architecture Rather than scattering our business logic in the controller and duplicating the data save code snippets all around, we use the repository pattern

Three Layer Architecture

Three Layer Architecture

The Repository pattern provides a flexibility in switching between data providers. Rather than hard coding the data access code in the application or service layer. then we decide to use XML database rather than SQL database, in this case we will have remove multiple copy-and-paste code from multiple places and change it with every time we need to make a change.

The Repository patterns provides a common unified abstract interface to deal with any data provider we might use later.

Repository pattern implementation in PHP

We will implement the repository pattern in PHP. This is a real code that I used in a laravel-based application.


The IRepository interface provides a unified interface for the basic CRUD operations.


The Repository class implements the IRepository interface and extends it with some operations.



You can access the Repository layer from the Service class.

The constructor receives a model and initiates it with the private repository object that is used to any data access operation.

You can then use the service object in any controller class.


Summary

In this tutorial we saw how the repository patterns provides the flexibility of changing the data provider as per requirement without the need to copy-and-paste or scatter the data access code across the application.

We Divided the application to three layers :

The application layer that is responsible for rendering views.

The Service Layer : that contains the business logic.

The Repository Layer : contains the data access logic .