Home >Backend Development >PHP Tutorial >Repository Design Pattern Demystified

Repository Design Pattern Demystified

Lisa Kudrow
Lisa KudrowOriginal
2025-02-21 08:54:13731browse

Repository Design Pattern Demystified

Core points

  • The warehouse pattern acts as an intermediary between the application and the data source, allowing the construction of a decoupled architecture to achieve scalability without the need for hard-coded dependencies.
  • This mode allows the application to focus on receiving and sending data for saving without paying attention to the details of the data source. It does this through a public API (interface) through which all users communicate with the data source.
  • While the warehouse pattern offers benefits such as separation of concerns and ease of unit testing, it also adds a layer of abstraction, which can complicate small applications.
  • Implementing the warehouse pattern requires dependency injection, which allows the data warehouse to be bound to the warehouse interface. This avoids hard-coded coupling and facilitates interface-oriented programming.

What is the warehouse model?

Simply put, it is an implementation of the intermediary layer between the application and the data source. Neither party needs to know each other to perform their respective tasks, which allows us to have a decoupled architecture that helps scale in large applications without hard-coded dependencies.

Why should you pay attention to it?

Let's understand this with an example. Suppose we are building an online store selling orange flavored candies. It's a small store that keeps local stock so we don't need anything fancy. Storefront applications can only connect to the database and take orders online based on existing inventory. This will work well as the store has only one supply warehouse and limited operating areas. But what happens if the store wants to expand its operating area? Stores may want to expand into another city or across the country, and having a central inventory system will be very troublesome.

If we still use the data model, then our application will be somewhat tightly coupled. Storefront applications need to know every data source it has to interact with, which is a bad application design. The job of a storefront application is to allow customers to order candy, the application should not care about the data source, it should not track all the different data sources. This is where data warehouses come into play. According to the warehouse pattern, a public API is exposed through an interface, and each consumer (in this case our storefront application) uses it to communicate with the data source. Which data source to use or how to connect to it is nothing to do with the application. The application only cares about the data it gets and the data it sends to save.

Once the warehouse pattern is implemented, a warehouse can be created for each data source. Storefront applications no longer need to track any data sources, it simply uses the repository API to get the data they need.

Is it a panacea?

No, it is not. Like every design pattern, it has its pros and cons.

Pros:

  • Separation of concerns; the application does not need to understand or track any or all data sources.
  • allows easy unit testing, as the repository is bound to an interface that injects the class at runtime.
  • DRY (Do not repeat yourself) design, the code for querying and obtaining data from the data source will not be repeated.

Disadvantages:

  • Add another layer of abstraction, adding a certain level of complexity, making it too complex for small applications.

How to do it?

Let's look at a simple code example. I'll use Laravel in my example to take advantage of its excellent dependency injection functionality. If you use any modern PHP framework, it should already have a dependency injection/IoC container. Implementing the warehouse pattern requires dependency injection, because without it you won't be able to bind your data warehouse to a warehouse interface, and the whole idea is interface-oriented programming to avoid hard-coded coupling. If you are not using any framework or the framework of your choice does not have an IoC container, you can use an off-the-shelf IoC container (see footnote).

Let's get started. First, we set up our namespace and autoload in Composer. Open composer.json and add psr-4 autoload to our namespace (in the autoload node, immediately after classmap).

<code class="language-json">    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ],
        "psr-4": {
            "RocketCandy\": "app/RocketCandy"
        }
    },</code>

After saving, execute composer dump-autoload -o in the terminal to register the automatic loading of the new namespace. Create app/RocketCandy/Repositories/OrangeCandyRepository/ in OrangeCandyRepository.php. This will be our repository interface.

<code class="language-php"><?php
namespace RocketCandy\Repositories\OrangeCandyRepository;

interface OrangeCandyRepository {

    public function get_list( $limit = 0, $skip = 0 );

    public function get_detail( $candy_id = 0 );

}</code>

Now that we have the interface, we can create a repository. Create app/RocketCandy/Repositories/OrangeCandyRepository/ in CityAOrangeCandyRepository.php.

<code class="language-php"><?php
namespace RocketCandy\Repositories\OrangeCandyRepository;

class CityAOrangeCandyRepository implements OrangeCandyRepository {

    public function get_list( $limit = 0, $skip = 0 ) {
        // 查询数据源并获取糖果列表
    }

    public function get_detail( $candy_id = 0 ) {
        // 查询数据源并获取糖果详情
    }

}</code>

To bind the CityAOrangeCandyRepository repository to the OrangeCandyRepository interface, we will utilize Laravel's IoC container. Open app/start/global.php and add the following to the end of the file.

<code class="language-php">//OrangeCandyRepository
App::bind(
    'RocketCandy\Repositories\OrangeCandyRepository\OrangeCandyRepository',
    'RocketCandy\Repositories\OrangeCandyRepository\CityAOrangeCandyRepository'
);</code>

Note: I only placed IoC bindings in global.php for demonstration. Ideally, these should be placed in their own separate files where you can put all IoC bindings and then load that file here in global.php or you can create a service provider to register each IoC Bind. You can read more here.

Now we can use the repository through the interface. In app/controllers/ located in CandyListingController.php.

<code class="language-json">    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php"
        ],
        "psr-4": {
            "RocketCandy\": "app/RocketCandy"
        }
    },</code>

Here, we inject the OrangeCandyRepository interface into our controller and store its object reference in a class variable that can now be used by any function in the controller to query data. Since we bind the OrangeCandyRepository interface to the CityAOrangeCandyRepository repository, it will be just like we use the CityAOrangeCandyRepository repository directly.

So, now, the type and type of data source are the only concerns of CityAOrangeCandyRepository. Our application only knows the OrangeCandyRepository interface and its exposed API, and each repository that implements it must comply with that API. The warehouse is parsed from the IoC container at runtime, which means that the interface warehouse binding can be set as needed. The interface can be bound to any data warehouse, and our application does not need to care about changes in the data source. The data source can now be a database, Web services or cross-dimensional hyperdata pipeline.

Not all cases apply

As I mentioned in the drawbacks of repository pattern, it adds some complexity to the application. So if you are making a small application and you don't see it evolve to the point where it's large (may require multiple data sources to be called), it's better not to implement it and stick to the old-style data model. Understanding something is different from knowing when to use it. This is a very convenient design pattern that saves a lot of trouble when creating applications and when you have to maintain or extend (or reduce) applications, but it is not a panacea for all applications.

I used Laravel specific code to demonstrate the above implementation, but it is fairly simple and similar for any good IoC container. Any questions? Please make it in the comments below.

Footnote:

  • The following are some IoC container libraries that you can use if your framework does not have or you do not use the framework:

    • OrnoDi
    • Ray.Di
    • Auryn
    • Dice
    • Bucket
    • Ding
  • Suggested reading:

    • Domain Driven Design Quickly
    • Domain-Driven Design by Eric Evans

Frequently Asked Questions about Warehouse Model

(This part of the content is highly coincidental with the original text. To avoid duplication, it is omitted here. The FAQ section in the original text has included a comprehensive explanation of the warehouse pattern.)

The above is the detailed content of Repository Design Pattern Demystified. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn