agungsugiarto/codeigniter4-repository

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

v1.1.0 2021-02-01 15:25 UTC

This package is auto-updated.

Last update: 2024-08-29 05:31:04 UTC


README

Latest Stable Version Total Downloads Latest Unstable Version License

关于

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

目录

安装

通过 Composer

$ composer require agungsugiarto/codeigniter4-repository

概述

包允许您根据传入请求的参数进行数据过滤
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',
        ['created_at', '>', Time::now()],
    ]),
    ...
])->get();

使用方法

创建模型

创建您的模型

namespace App\Models;

use CodeIgniter\Model;

class News extends Model 
{
    ...
}

创建仓库

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

namespace App;

use App\Models\News;
use Fluent\Repository\Eloquent\BaseRepository;

class NewsRepository extends BaseRepository
{
    public function entity()
    {
        // Whatever choose one your style.

        return new News();
        // or
        return 'App\Models\News';
        // or
        return News::class;
    }
}

使用内置方法

use App\NewsRepository;

class NewsController extends BaseController 
{
    protected $news;

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

可用方法

  • 作为 "select" 语句执行查询或获取所有结果
/**
 * Get method implement parameter "select", "limit" and "offset".
 * The default will be select * and return all offset data.
 * 
 * Example: $this->news->get(['*'], 50, 100);
 */
$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'],
        ...
    ]);
  • 分页给定查询

注意:有关 "paginate": {} 可用方法的详细信息,请参阅 文档

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

// return will be
{
    "data": [
        {
            "id": "3",
            "title": "Ms. Carole Wilderman DDS",
            "content": "Labore id aperiam ut voluptatem eos natus.",
            "created_at": "2020-08-05 17:07:16",
            "updated_at": "2020-08-05 17:07:16",
            "deleted_at": null
        },
        ...
     ],
    "paginate": {}
}
  • 向查询添加 "order by" 子句
$news = $this->news->orderBy('title', 'desc')->get();
  • 保存新模型并返回实例
$news = $this->news->create($this->request->getVar());
  • 批量保存新模型并返回实例
$data = [
    [
        'title' => 'My title',
        'name'  => 'My Name',
        'date'  => 'My date'
    ],
    [
        'title' => 'Another title',
        'name'  => 'Another Name',
        'date'  => 'Another date'
    ]
];

$news = $this->news->createBatch($data);
  • 更新记录
$this->news->update($this->request->getVar(), $id);
  • 批量更新记录
$data = [
    [
        'title' => 'My title',
        'name'  => 'My Name',
        'date'  => 'My date'
    ],
    [
        'title' => 'Another title',
        'name'  => 'Another Name',
        'date'  => 'Another date'
    ]
];

$news = $this->news->updateBatch($data, 'title');
  • 按 ID 删除记录
$this->news->destroy($id);

创建标准

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

use Fluent\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()
    {
        $this->news = new NewsRepository();
    }

    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()
{
    return $this->news->scope($this->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($this->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(IncomingRequest $request)
{
    // apply build-in scopes
    parent::scope($request);

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

    return $this;
}

创建您的 scopes 类并扩展 ScopesAbstract

use Fluent\Repository\Scopes\ScopesAbstract;

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

现在您可以根据需要构建任何范围

use Fluent\Repository\Scopes\ScopeAbstract;

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

许可证

在 MIT 许可证下发布,请参阅 LICENSE