awes-io/repository

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

v1.1.8 2021-06-01 13:34 UTC

README

Awes.io 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 awes-io/repository

该软件包将自动注册自身。

配置

首先发布配置

php artisan vendor:publish --provider="AwesIO\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 
{
    ...
}

创建仓库

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

namespace App;

use AwesIO\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 AwesIO\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 将按降序排序 email,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 AwesIO\Repository\Scopes\ScopesAbstract;

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

现在您可以构建所需的任何范围

use AwesIO\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

测试

该软件包的覆盖范围如下所示:覆盖报告

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

composer test

贡献

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

致谢

许可证

MIT