search
HomePHP FrameworkLaravelA brief analysis of the advantages of the repository pattern (Repository) in Laravel

Why use the repository pattern (Repository) in Laravel? The following article will introduce to you the advantages of using the repository mode. I hope it will be helpful to you!

A brief analysis of the advantages of the repository pattern (Repository) in Laravel

In a previous article, I explained what the repository pattern is, how it differs from the Active Record pattern, and how to implement it in Laravel. Now I want to take a closer look at why you should use the repository pattern.

I noticed in the comments of the previous article that the Repository pattern is a controversial topic in the Laravel community. Some people see no reason to use it and stick with the built-in Active Record mode. Others prefer to use other methods to separate data access from the logical domain. Please note that I respect these opinions and will devote an upcoming blog post to this topic.

With this disclaimer, let’s understand the advantages of using the repository pattern.

Single Responsibility Principle

The Single Responsibility Principle is the main discriminator to differentiate between Active Record mode and Repository mode. Model classes already hold data and provide methods on domain objects. When using the Active Record pattern, data access is an additional responsibility introduced. This is something I want to illustrate in the following example:

/**
 * @property string $first_name
 * @property int    $company_id
 */
class Employee extends Model {}

$jack = new Employee();
$jack->first_name = 'Jack';
$jack->company_id = $twitterId;
$jack->save();

Although the domain model and data access technology have mixed responsibilities, it intuitively makes sense. In our application the employees have to be stored in the database somehow, so why not call save() on the object. A single object is converted into a single row of data and stored.

But let's go a step further and see what else we can do with employees:

$jack->where('first_name', 'John')->firstOrFail()->delete();
$competition = $jack->where('company_id', $facebookId)->get();

Now, it becomes unintuitive and even violates our domain model. Why would Jack suddenly delete another employee who might even be working at a different company? Or why he was able to bring Facebook employees over?

Of course, this example is contrived, but it still shows how the Active Record pattern does not allow for intentional domain models. The line between employees and the list of all employees becomes blurred. You always have to consider whether the employee is being used as an actual employee or as a mechanism to access other employees.

Warehouse mode solves this problem by enforcing this basic partitioning. Its only purpose is to identify a collection of domain objects, not the domain object itself.

Key points:

  • #The warehouse pattern embodies the single responsibility principle by separating a collection of all domain objects from a single domain object.
Some projects sprinkle database queries all over the project. Below is an example where we get a list from the database and display them in a Blade view.

class InvoiceController {

    public function index(): View {
        return view('invoices.index', [
            'invoices' => Invoice::where('overdue_since', '>=', Carbon::now())
                ->orderBy('overdue_since')
                ->paginate()
        ]);
    }
}

When a query like this becomes more complex and used in multiple places, consider extracting it into a Repository method.

The repository pattern helps reduce duplicate queries by packaging them into expression methods. If you have to adjust the query, you only need to change it once.

class InvoiceController {

    public __construct(private InvoiceRepository $repo) {}

    public function index(): View {
        return view('invoices.index', [
            'invoices' => $repo->paginateOverdueInvoices()
        ]);
    }
}

Now the query is implemented only once and can be tested in isolation and used elsewhere. Additionally, the Single Responsibility Principle comes into play again, as the controller is not responsible for getting the data, but only for processing the HTTP request and returning the response.

Takeaway:

    ? Repository pattern helps reduce duplicate queries

Dependency Inversion

Explanation

Dependency Inversion Principle It deserves its own blog post. I just wanted to illustrate that a repository can enable dependency inversion.

When layering components, typically higher-level components depend on lower-level components. For example, the controller will rely on the model class to get data from the database:

class InvoiceController {
    public function index(int $companyId): View {
        return view(
            'invoices.index',
            ['invoices' => Invoice::where('company_id', $companyId)->get()]
        );
    }
}

The dependency is top-down and tightly coupled.

InvoiceController depends on the specific Invoice class. It is difficult to decouple these two classes, such as testing them separately or replacing the storage mechanism. By introducing the Repository interface, we can achieve dependency inversion:

interface InvoiceRepository {
    public function findByCompanyId($companyId): Collection;
}

class InvoiceController {
    public function __construct(private InvoiceRepository $repo) {}

    public function index(int $companyId): View {
        return view(
            'invoices.index',
            ['invoices' => $this->repo->findByCompanyId($companyId)]
        );
    }
}

class EloquentInvoiceRepository implements InvoiceRepository {
    public function findByCompanyId($companyId): Collection {
        // 使用 Eloquent 查询构造器实现该方法
    }
}

Controller now only depends on the Repository interface, the same as the Repository implementation.

These two classes now only depend on one abstraction, thus reducing Coupling. As I will explain in the next section, this brings further advantages.

Takeaway:

  • ? 存储库模式作为一种抽象类,支持依赖反转.

存储库 提高了可读性 因为复杂的操作被具有表达性名称的高级方法隐藏了.

访问存储库的代码与底层数据访问技术分离. 如有必要,您可以切换实现,甚至可以省略实现,仅提供 Repository 接口。 这对于旨在与框架无关的库来说非常方便。

OAuth2 服务包 ——  league/oauth2-server 也用到这个抽象类机制。 Laravel Passport 也通过 实现这个库的接口 集成 league/oauth2-server 包。

正如 @bdelespierre评论 里回应我之前的一篇博客文章时向我指出的那样,你不仅可以切换存储库实现,还可以将它们组合在一起。大致以他的示例为基础,您可以看到一个存储库如何包装另一个存储库以提供附加功能:

interface InvoiceRepository {
    public function findById(int $id): Invoice;
}

class InvoiceCacheRepository implements InvoiceRepository {

    public function __construct(
        private InvoiceRepository $repo,
        private int $ttlSeconds
    ) {}

    public function findById(int $id): Invoice {
        return Cache::remember(
            "invoice.$id",
            $this->ttlSeconds,
            fn(): Invoice => $this->repo->findById($id)
        );
    }
}

class EloquentInvoiceRepository implements InvoiceRepository {

    public function findById(int $id): Invoice { /* 从数据库中取出 $id */ }
}

// --- 用法:

$repo = new InvoiceCacheRepository(
    new EloquentInvoiceRepository();
);

要点:

  • ? 存储库模式抽象了有关数据访问的详细信息。
  • ? 存储库将客户端与数据访问技术分离
  • ? 这允许切换实现,提高可读性并实现可组合性。

可测试性

存储库模式提供的抽象也有助于测试。

如果你有一个 Repository 接口,你可以提供一个替代的测试实现。 您可以使用数组支持存储库,而不是访问数据库,将所有对象保存在数组中:

class InMemoryInvoiceRepository implements InvoiceRepositoryInterface {

    private array $invoices;

    // implement the methods by accessing $this->invoices...
}

// --- Test Case:

$repo = new InMemoryInvoiceRepository();
$service = new InvoiceService($repo);

通过这种方法,您将获得一个现实的实现,它速度很快并且在内存中运行。 但是您必须为测试提供正确的 Repository 实现,这 ** 本身可能需要大量工作**。 在我看来,这在两种情况下是合理的:

  • 您正在开发一个(与框架无关的)库,它本身不提供存储库实现。

  • 测试用例复杂,Repository 的状态很重要。

另一种方法是“模仿”,要使用这种技术,你不需要适当的接口。你可以模仿任何 non-final 类。
使用 PHPUnit API ,您可以明确规定如何调用存储库以及应该返回什么。

$companyId = 42;

/** @var InvoiceRepository&MockObject */
$repo = $this->createMock(InvoiceRepository::class);

$repo->expects($this->once())
    ->method('findInvoicedToCompany')
    ->with($companyId)
    ->willReturn(collect([ /* invoices to return in the test case */ ]));

$service = new InvoiceService($repo);

$result = $service->calculateAvgInvoiceAmount($companyId);

$this->assertEquals(1337.42, $result);

有了 mock,测试用例就是一个适当的单元测试。上面示例中测试的唯一代码是服务。没有数据库访问,这使得测试用例的设置和运行非常快速

另外:

  • ? 仓库模式允许进行适当的单元测试,这些单元测试运行快并且是隔离的

原文地址:https://dev.to/davidrjenni/why-use-the-repository-pattern-in-laravel-2j1m

译文地址:https://learnku.com/laravel/t/62521

【相关推荐:laravel视频教程

The above is the detailed content of A brief analysis of the advantages of the repository pattern (Repository) in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
Laravel in Action: Real-World Applications and ExamplesLaravel in Action: Real-World Applications and ExamplesApr 16, 2025 am 12:02 AM

Laravelcanbeeffectivelyusedinreal-worldapplicationsforbuildingscalablewebsolutions.1)ItsimplifiesCRUDoperationsinRESTfulAPIsusingEloquentORM.2)Laravel'secosystem,includingtoolslikeNova,enhancesdevelopment.3)Itaddressesperformancewithcachingsystems,en

Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools