awema-pl/module-repository

Laravel 的仓库模式实现。该软件包允许根据请求中的参数进行开箱即用的数据过滤,并且允许您快速集成列表过滤器以及自定义标准。

v1.0.10 2021-01-21 22:08 UTC

This package is auto-updated.

Last update: 2024-09-22 06:15:07 UTC


README

Awema.pl logo

仓库

Laravel 中的仓库模式。该软件包允许开箱即用地通过请求进行过滤,并允许集成自定义标准及任何类型的过滤器。

Coverage report Last version Build status Downloads License CDN Ready laravel Last commit Analytics Hosted by Package Kit Patreon

Repository Laravel

目录

安装

通过 Composer

$ composer require awema-pl/module-repository

软件包将自动注册自己。

配置

首先发布配置

php artisan vendor:publish --provider="AwemaPL\Repository\RepositoryServiceProvider" --tag="config"
// $repository->smartPaginate() related parameters
'smart_paginate' => [
    // name of request parameter to take paginate by value from
    'request_parameter' => 'limit',
    // default paginate by value
    'default_limit' => 15,
    // max paginate by value
    'max_limit' => 100,
]

概述

软件包允许您根据传入的请求参数过滤数据
https://example.com/news?title=Title&custom=value&orderBy=name_desc

它将自动将内置约束应用于查询,以及您需要的任何自定义作用域和标准

protected $searchable = [
    // where 'title' equals 'Title'
    'title',
];

protected $scopes = [
    // and custom parameter used in your scope
    'custom' => MyScope::class,
];
class MyScope extends ScopeAbstract
{
    public function scope($builder, $value, $scope)
    {
        return $builder->where($scope, $value)->orWhere(...);
    }
}

可以根据任何字段进行排序

protected $scopes = [
    // orderBy field
    'orderBy' => OrderByScope::class,
];

软件包还可以应用任何自定义标准

return $this->news->withCriteria([
    new MyCriteria([
        'category_id' => '1', 'name' => 'Name'
    ])
    ...
])->get();

使用方法

创建模型

创建您的模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class News extends Model 
{
    ...
}

创建仓库

AwemaPL\Repository\Eloquent\BaseRepository 扩展它,并提供 entity() 方法以返回完整的模型类名

namespace App;

use AwemaPL\Repository\Eloquent\BaseRepository;

class NewsRepository extends BaseRepository
{
    public function entity()
    {
        return News::class;
    }
}

使用内置方法

use App\NewsRepository;

class NewsController extends BaseController 
{
    protected $news;

    public function __construct(NewsRepository $news)
    {
        $this->news = $news;
    }
    ....
}

执行查询作为“选择”语句或获取所有结果

$news = $this->news->get();

执行查询并获取第一个结果

$news = $this->news->first();

通过其主键查找模型

$news = $this->news->find(1);

添加基本 WHERE 子句并执行查询

$news = $this->news->->findWhere([
        // where id equals 1
        'id' => '1',
        // other "where" operations
        ['news_category_id', '<', '3'],
        ...
    ]);

分页给定的查询

$news = $this->news->paginate(15);

将给定的查询分页到一个简单的分页器

$news = $this->news->simplePaginate(15);

通过 'limit' 请求参数分页给定的查询

$news = $this->news->smartPaginate();

向查询添加一个“order by”子句

$news = $this->news->orderBy('title', 'desc')->get();

保存新的模型并返回实例

$news = $this->news->create($request->all());

更新记录

$this->news->update($request->all(), $id);

按 id 删除记录

$this->news->destroy($id);

将模型附加到父级

$this->news->attach($parentId, $relationship, $idsToAttach);

从关系断开模型

$this->news->detach($parentId, $relationship, $idsToDetach);

查找模型或如果没有找到则抛出异常

$this->news->findOrFail($id);

执行查询并获取第一个结果或抛出异常

$this->news->firstOrFail();

创建标准

标准是构建特定查询条件的一种方式。

use AwemaPL\Repository\Contracts\CriterionInterface;

class MyCriteria implements CriterionInterface {

    protected $conditions;
    
    public function __construct(array $conditions)
    {
        $this->conditions = $conditions;
    }

    public function apply($entity)
    {
        foreach ($this->conditions as $field => $value) {
            $entity = $entity->where($field, '=', $value);
        }
        return $entity;
    }
}

可以应用多个标准

use App\NewsRepository;

class NewsController extends BaseController 
{
    protected $news;

    public function __construct(NewsRepository $news)
    {
        $this->news = $news;
    }

    public function index()
    {
        return $this->news->withCriteria([
            new MyCriteria([
                'category_id' => '1', 'name' => 'Name'
            ]),
            new WhereAdmin(),
            ...
        ])->get();
    }
}

作用域、过滤和排序

在您的仓库中,通过设置 $searchable 属性来定义哪些字段可用于作用域您的查询。

protected $searchable = [
    // where 'title' equals parameter value
    'title',
    // orWhere equals
    'body' => 'or',
    // where like
    'author' => 'like',
    // orWhere like
    'email' => 'orLike',
];

按可搜索项搜索

public function index($request)
{
    return $this->news->scope($request)->get();
}
https://example.com/news?title=Title&body=Text&author=&email=gmail

还启用了默认的几个可搜索项

protected $scopes = [
    // orderBy field
    'orderBy' => OrderByScope::class,
    // where created_at date is after
    'begin' => WhereDateGreaterScope::class,
    // where created_at date is before
    'end' => WhereDateLessScope::class,
];
$this->news->scope($request)->get();

通过将 $orderable 属性添加到您的模型类中,为特定字段启用排序

public $orderable = ['email'];
https://example.com/news?orderBy=email_desc&begin=2019-01-24&end=2019-01-26

orderBy=email_desc 将按降序对电子邮件进行排序,orderBy=email - 按升序

您还可以构建自己的自定义作用域。在您的仓库中重写 scope() 方法

public function scope($request)
{
    // apply build-in scopes
    parent::scope($request);

    // apply custom scopes
    $this->entity = (new NewsScopes($request))->scope($this->entity);

    return $this;
}

创建您的 scopes 类并扩展 ScopesAbstract

use AwemaPL\Repository\Scopes\ScopesAbstract;

class NewsScopes extends ScopesAbstract
{
    protected $scopes = [
        // here you can add field-scope mappings
        'field' => MyScope::class,
    ];
}

现在您可以构建所需的任何作用域

use AwemaPL\Repository\Scopes\ScopeAbstract;

class MyScope extends ScopeAbstract
{
    public function scope($builder, $value, $scope)
    {
        return $builder->where($scope, $value);
    }
}

Artisan 命令

软件包提供了有用的 artisan 命令

php artisan repository:generate Models/Order --scope=Search

它将为 App\Models\Order 生成几个类

主要仓库:App\Repositories\Orders\OrdersRepository

主要作用域类:App\Repositories\Orders\Scopes\OrdersScopes

单个搜索作用域类:App\Repositories\Orders\Scopes\SearchOrdersScope

测试

该软件包的覆盖率报告为 Coverage report

您可以使用以下命令运行测试

composer test

贡献

请参阅 contributing.md 以获取详细信息和一个待办事项列表。

致谢

许可证

MIT许可证