chr15k/laravel-repository

此包已被弃用,不再维护。没有建议替代包。

Laravel 的仓库层设计模式

2.0.1 2021-03-20 11:18 UTC

This package is auto-updated.

Last update: 2022-11-20 15:06:35 UTC


README

Latest Stable Version Latest Unstable Version Total Downloads License

Laravel Repository 是用于 Laravel 5 / 6 / 7 的一个包。它用于将业务逻辑抽象到仓库层,目的是保持代码库的清洁和可维护性。

 $this->app->bind(
    'App\Repositories\Contracts\UserRepositoryInterface', // <-- injected into controller constructor
    'App\Repositories\Eloquent\UserRepository' // <-- Repo class
);

安装

您可以通过 composer 安装此包

composer require chr15k/laravel-repository

如果您没有运行 Laravel 5.5(或更高版本),请在 config/app.php 中添加服务提供者

Chr15k\Repository\RepositoryServiceProvider::class,

发布配置以自定义模型和仓库文件路径。

php artisan vendor:publish --provider="Chr15k\Repository\RepositoryServiceProvider"

更新配置文件以设置模型路径 - 默认为 app/Models

设置

步骤 1 运行以下命令(将名称设置为您相关模型的名称)

php artisan make:repository User

这将在 app/Repositories 内创建以下文件

├── Repositories
│   ├── Contracts
│   │   └── UserRepositoryInterface.php
│   └── Eloquent
│       └── UserRepository.php

步骤 2 将以下内容添加到您的 app/Providers/AppServiceProvider.php 文件的 register() 方法中

$this->app->bind(
    'App\Repositories\Contracts\UserRepositoryInterface',
    'App\Repositories\Eloquent\UserRepository'
);

步骤 3 只需将接口注入到控制器的构造方法中,Laravel 将管理类依赖项

<?php

namespace App\Http\Controllers;

use App\Repositories\Contracts\UserRepositoryInterface;

class UserController extends Controller
{
    protected $userRepo;

    public function __construct(UserRepositoryInterface $userRepo)
    {
        $this->userRepo = $userRepo;
    }

    public function index()
    {
        $users = $this->userRepo->all();

        return view('users.index', compact('users'));
    }

    public function show($id)
    {
        $user = $this->userRepo->find($id);

        return view('users.show', compact('user'));
    }
}

只需将任何自定义方法添加到 UserRepository.phpUserRepositoryInterface.php,然后即可使用!如果任何其他控制器需要使用相同的复杂查询,现在它已经集中在一个位置。新的实现可以在 AppServiceProvider.php 中进行交换,而不需要更改其他任何内容。

$users = $this->userRepo->someComplexQuery();

用法

默认情况下,以下方法可用于您的仓库。如果您需要访问此处未包含的方法,则只需调用 model() 方法以从仓库中获取模型实例。

所有获取方法都接受一个 related 数组以预加载关系。

您还可以通过调用 errors() 获取最后操作的最新错误。

    $this->repo->all($related = []);
    $this->repo->chunk($size, $callback);
    $this->repo->cursor();
    $this->repo->create($attributes = [], $related = []);
    $this->repo->destroy($id);
    $this->repo->errors();
    $this->repo->find($id, $related = []);
    $this->repo->findOrFail($id, $related = []);
    $this->repo->findOrNew($id, $related = []);
    $this->repo->getNew($attributes = []);
    $this->repo->model();
    $this->repo->paginate($perPage, $related = []);
    $this->repo->update($id, $attributes = [], $related = []);

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件