deva7mad/laravel-repositories

Rinvex Repository 是一个简单、直观、智能的 Active Repository 实现,为 Laravel 提供了极其灵活且细粒度的缓存系统,用于抽象数据层,使应用程序更易于维护。

1.0 2018-10-23 09:13 UTC

This package is auto-updated.

Last update: 2024-09-24 04:44:06 UTC


README

Rinvex Repository Diagram

Rinvex Repository 是一个简单、直观、智能的 Active Repository 实现,为 Laravel 提供了极其灵活且细粒度的缓存系统,用于抽象数据层,使应用程序更易于维护。

Packagist Scrutinizer Code Quality Code Climate Travis StyleCI License

💡 如果你需要 Laravel 5.5 支持,请使用 dev-develop 分支。它已稳定,但尚未标记,因为测试套件尚未完成。 💡

⚠️ 此包正在寻找新的维护者,感兴趣的话请阅读详细信息或接管! ⚠️

功能

  • 缓存,缓存,缓存!
  • 防止代码重复。
  • 减少潜在的编程错误。
  • 以灵活的方式细粒度缓存查询。
  • 应用集中管理、一致的访问规则和逻辑。
  • 实现并集中管理领域模型的缓存策略。
  • 通过将客户端对象与领域模型分离,提高代码的可维护性和可读性。
  • 通过自动化和隔离客户端对象和领域模型以支持单元测试,最大化可测试的代码量。
  • 将行为与相关数据相关联。例如,计算字段或强制执行实体内数据元素之间的复杂关系或业务规则。

快速示例(TL;DR)

Rinvex\Repository\Repositories\BaseRepository 是一个抽象类,具体的实现必须扩展它。

Rinvex\Repository\Repositories\EloquentRepository 目前是唯一可用的仓库实现(未来将会有更多,你还可以开发自己的),它使创建新的 Eloquent 模型实例并轻松操作它们变得简单。要使用 EloquentRepository,你的仓库必须首先扩展它

namespace App\Repositories;

use Rinvex\Repository\Repositories\EloquentRepository;

class FooRepository extends EloquentRepository
{
    protected $repositoryId = 'rinvex.repository.uniqueid';

    protected $model = 'App\Models\User';
}

就是这样,你已经完成了!是的,就是这样简单。

但是,如果你想对容器实例有更多控制,或者想动态传递模型名称,你可以采取以下做法

namespace App\Repositories;

use Illuminate\Contracts\Container\Container;
use Rinvex\Repository\Repositories\EloquentRepository;

class FooRepository extends EloquentRepository
{
    // Instantiate repository object with required data
    public function __construct(Container $container)
    {
        $this->setContainer($container)
             ->setModel(\App\Models\User::class)
             ->setRepositoryId('rinvex.repository.uniqueid');

    }
}

现在在你的控制器中,你可以通过 $repository = new \App\Repositories\FooRepository(); 传统的创建仓库实例,或者使用 Laravel 的出色依赖注入和 IoC 来完成这项工作

namespace App\Http\Controllers;

use App\Repositories\FooRepository;

class BarController
{
    // Inject `FooRepository` from the IoC
    public function baz(FooRepository $repository)
    {
        // Find entity by primary key
        $repository->find(1);

        // Find all entities
        $repository->findAll();

        // Create a new entity
        $repository->create(['name' => 'Example']);
    }
}

Rinvex Repository 工作流程 - 创建仓库 Rinvex Repository 工作流程 - 创建仓库

Rinvex Repository 工作流程 - 在控制器中使用 Rinvex Repository 工作流程 - 在控制器中使用

UML 图

任务完成!你现在可以使用这个包了!✅

除非你需要深入了解并了解一些高级内容,否则你可以跳过以下步骤!😉

目录

安装

安装此包的最佳和最简单的方式是通过Composer

兼容性

此包完全兼容Laravel 5.1.*, 5.2.*, 和 5.3.*

虽然此包倾向于框架无关性,但它在一定程度上接纳了Laravel文化和最佳实践。它主要与Laravel进行测试,但您仍然可以使用它与其他框架或根本不需要框架。

需要包

打开您的应用程序的composer.json文件,并在require数组中添加以下行

"rinvex/laravel-repositories": "3.0.*"

注意:确保在所需更改后通过运行composer validate验证您的composer.json文件是否有效。

安装依赖项

在您的终端中运行composer installcomposer update命令,根据您的应用程序状态安装新要求。

注意:有关更多详细信息,请参阅Composer的基本用法文档。

集成

Rinvex Repository包是框架无关的,因此可以轻松地本地集成或与您喜欢的框架集成。

本地集成

在框架之外集成此包非常简单,只需包含vendor/autoload.php文件来自动加载包。

注意:有关更多详细信息,请参阅Composer的自动加载文档。

在您的终端中运行以下命令以发布配置文件

php artisan vendor:publish --tag="rinvex-repository-config"

注意:有关更多详细信息,请参阅Laravel的配置文档。

您已经准备好。集成完成,您现在可以使用所有可用方法,转到使用方法部分以获取示例。

配置

如果您遵循了先前的集成步骤,那么您的发布配置文件位于config/rinvex.repository.php

配置选项非常直观,如下所示

return [

    /*
    |--------------------------------------------------------------------------
    | Models Directory
    |--------------------------------------------------------------------------
    |
    | Here you may specify the default models directory, just write
    | directory name, like 'Models' not the full path.
    |
    | Default: 'Models'
    |
    */

    'models' => 'Models',

    /*
    |--------------------------------------------------------------------------
    | Caching Strategy
    |--------------------------------------------------------------------------
    */

    'cache' => [

        /*
        |--------------------------------------------------------------------------
        | Cache Keys File
        |--------------------------------------------------------------------------
        |
        | Here you may specify the cache keys file that is used only with cache
        | drivers that does not support cache tags. It is mandatory to keep
        | track of cache keys for later usage on cache flush process.
        |
        | Default: storage_path('framework/cache/rinvex.repository.json')
        |
        */

        'keys_file' => storage_path('framework/cache/rinvex.repository.json'),

        /*
        |--------------------------------------------------------------------------
        | Cache Lifetime
        |--------------------------------------------------------------------------
        |
        | Here you may specify the number of minutes that you wish the cache
        | to be remembered before it expires. If you want the cache to be
        | remembered forever, set this option to -1. 0 means disabled.
        |
        | Default: -1
        |
        */

        'lifetime' => -1,

        /*
        |--------------------------------------------------------------------------
        | Cache Clear
        |--------------------------------------------------------------------------
        |
        | Specify which actions would you like to clear cache upon success.
        | All repository cached data will be cleared accordingly.
        |
        | Default: ['create', 'update', 'delete']
        |
        */

        'clear_on' => [
            'create',
            'update',
            'delete',
        ],

        /*
        |--------------------------------------------------------------------------
        | Cache Skipping URI
        |--------------------------------------------------------------------------
        |
        | For testing purposes, or maybe some certain situations, you may wish
        | to skip caching layer and get fresh data result set just for the
        | current request. This option allows you to specify custom
        | URL parameter for skipping caching layer easily.
        |
        | Default: 'skipCache'
        |
        */

        'skip_uri' => 'skipCache',

    ],

];

使用方法

详细文档

setContainer(), getContainer()

setContainer方法设置IoC容器实例,而getContainer返回它

// Set the IoC container instance
$repository->setContainer(new \Illuminate\Container\Container());

// Get the IoC container instance
$container = $repository->getContainer();

setConnection(), getConnection()

setConnection方法设置与仓库关联的连接,而getConnection返回它

// Set the connection associated with the repository
$repository->setConnection('mysql');

// Get the current connection for the repository
$connection = $repository->getConnection();

注意:传递给setConnection方法的名称应与您的config/database.php配置文件中列出的连接之一相匹配。

setModel(), getModel()

setModel方法设置仓库模型,而getModel返回它

// Set the repository model
$repository->setModel(\App\Models\User::class);

// Get the repository model
$repositoryModel = $repository->getModel();

setRepositoryId(), getRepositoryId()

setRepositoryId方法设置仓库标识符,而getRepositoryId返回它(可以是任何您想要的,但必须是每个仓库的唯一标识符)

// Set the repository identifier
$repository->setRepositoryId('rinvex.repository.uniqueid');

// Get the repository identifier
$repositoryId = $repository->getRepositoryId();

setCacheLifetime(), getCacheLifetime()

setCacheLifetime 方法用于设置仓库缓存的生存时间,而 getCacheLifetime 方法则返回它

// Set the repository cache lifetime
$repository->setCacheLifetime(123);

// Get the repository cache lifetime
$cacheLifetime = $repository->getCacheLifetime();

setCacheDriver(), getCacheDriver()

setCacheDriver 方法用于设置仓库缓存驱动程序,而 getCacheDriver 方法则返回它

// Set the repository cache driver
$repository->setCacheDriver('redis');

// Get the repository cache driver
$cacheDriver = $repository->getCacheDriver();

enableCacheClear(), isCacheClearEnabled()

enableCacheClear 方法用于启用仓库缓存清除,而 isCacheClearEnabled 方法用于确定其状态

// Enable repository cache clear
$repository->enableCacheClear(true);

// Disable repository cache clear
$repository->enableCacheClear(false);

// Determine if repository cache clear is enabled
$cacheClearStatus = $repository->isCacheClearEnabled();

createModel()

createModel() 方法用于创建一个新的仓库模型实例

$repositoryModelInstance = $repository->createModel();

forgetCache()

forgetCache() 方法用于忘记仓库缓存

$repository->forgetCache();

with()

with 方法用于设置应预加载的关系

// Pass a string
$repository->with('relationship');

// Or an array
$repository->with(['relationship1', 'relationship2']);

where()

where 方法用于向查询中添加基本的 where 子句

$repository->where('slug', '=', 'example');

whereIn()

whereIn 方法用于向查询中添加 "where in" 子句

$repository->whereIn('id', [1, 2, 5, 8]);

whereNotIn()

whereNotIn 方法用于向查询中添加 "where not in" 子句

$repository->whereNotIn('id', [1, 2, 5, 8]);

whereHas()

whereHas 方法用于向查询中添加 "where has relationship" 子句

use Illuminate\Database\Eloquent\Builder;

$repository->whereHas('attachments', function (Builder $builder) use ($attachment) {
    $builder->where('attachment_id', $attachment->id);
});

注意:所有 where* 方法都是可链的,可以在单个请求中多次调用。它将内部维护一个数组,在执行查询之前应用所有 where 子句。

offset()

offset 方法用于设置查询的 "offset" 值

$repository->offset(5);

limit()

limit 方法用于设置查询的 "limit" 值

$repository->limit(9);

orderBy()

orderBy 方法用于向查询中添加 "order by" 子句

$repository->orderBy('id', 'asc');

find()

find 方法用于通过主键查找实体

$entity = $repository->find(1);

findOrFail()

findOrFail() 方法用于通过主键查找实体或抛出异常

$entity = $repository->findOrFail(1);

findOrNew()

findOrNew() 方法用于通过主键查找实体或返回新的实体实例

$entity = $repository->findOrNew(1);

findBy()

findBy 方法用于通过一个属性查找实体

$entity = $repository->findBy('id', 1);

findFirst()

findFirst 方法用于查找第一个实体

$firstEntity = $repository->findFirst();

findAll()

findAll 方法用于查找所有实体

$allEntities = $repository->findAll();

paginate()

paginate 方法用于分页所有实体

$entitiesPagination = $repository->paginate(15, ['*'], 'page', 2);

正如你所猜想的,这是查询第一页的前15条记录。

simplePaginate()

simplePaginate 方法用于将所有实体分页到简单的分页器中

$entitiesSimplePagination = $repository->simplePaginate(15);

findWhere()

findWhere 方法用于查找所有匹配 where 条件的实体

// Matching values with equal '=' operator
$repository->findWhere(['slug', '=', 'example']);

findWhereIn()

findWhereIn 方法用于查找所有匹配 whereIn 条件的实体

$includedEntities = $repository->findwhereIn(['id', [1, 2, 5, 8]]);

findWhereNotIn()

findWhereNotIn 方法用于查找所有匹配 whereNotIn 条件的实体

$excludedEntities = $repository->findWhereNotIn(['id', [1, 2, 5, 8]]);

findWhereHas()

findWhereHas 方法用于查找所有匹配 whereHas 条件的实体

use Illuminate\Database\Eloquent\Builder;

$entities = $repository->findWhereHas(['attachments', function (Builder $builder) use ($attachment) {
    $builder->where('attachment_id', $attachment->id);
}]);

注意

  • findWhereHas 方法将返回匹配闭包内条件的实体集合。如果你需要嵌入 attachments 关系,在这种情况下,你需要在调用 findWhereHas() 之前调用 with() 方法,如下所示:$repository->with('attachments')->findWhereHas([...]);
  • v2.0.0 版本开始,所有 findWherefindWhereInfindWhereNotIn 方法的签名都已更改。
  • 所有 findWherefindWhereInfindWhereNotIn 方法分别使用 wherewhereInwhereNotIn 方法,因此第一个参数是后面所需参数的数组。
  • 所有 find* 方法都可以使用前面的 where 子句进行过滤,这些子句可以通过链式调用。所有 where 子句在内部存储在一个数组中,并在执行查询之前应用。请查看以下示例

findAll 方法的过滤示例

$allFilteredEntities = $repository->where('slug', '=', 'example')->findAll();

具有链式子句的 findFirst 方法的另一个示例

$allFilteredEntities = $repository->where('name', 'LIKE', '%TEST%')->where('slug', '=', 'example')->findFirst();

create()

create 方法用于创建具有给定属性的新的实体

$createdEntity = $repository->create(['name' => 'Example']);

update()

update 方法用于使用给定属性更新实体

$updatedEntity = $repository->update(1, ['name' => 'Example2']);

store()

store 方法用于使用给定属性存储实体

// Existing Entity
$storedEntity = $repository->store(1, ['name' => 'Example2']);

// New Entity
$storedEntity = $repository->store(null, ['name' => 'Example2']);

注意:此方法只是 createupdate 方法的别名。在单表用于创建和更新过程的情况下非常有用。

delete()

delete 方法用于根据给定 id 删除实体

$deletedEntity = $repository->delete(1);

beginTransaction()

beginTransaction 方法用于开始数据库事务

$repository->beginTransaction();

commit()

《commit`方法提交数据库事务

$repository->commit();

rollBack()

《rollback`方法回滚数据库事务

$repository->rollBack();

注意

  • 所有《find*`方法都接受一个额外的可选参数,用于选择属性。
  • 所有《set*`方法返回当前存储库的实例,因此可以进行链式调用。
  • 《create`、《update`和《delete`方法始终返回一个包含两个值的数组,第一个值是操作状态(成功或失败)作为布尔值,第二个值是刚刚操作的模型实例。
  • 建议像上面示例那样,通过存储库构造函数显式设置IoC容器实例、存储库模型和存储库标识符。但这个包足够智能,可以猜测任何缺失的要求。查看自动猜测部分

将代码转换为接口

作为最佳实践,建议为接口编码,特别是对于可扩展的项目。以下示例解释了如何这样做。

首先,为每个实体创建一个接口(抽象)

use Rinvex\Repository\Contracts\CacheableContract;
use Rinvex\Repository\Contracts\RepositoryContract;

interface UserRepositoryContract extends RepositoryContract, CacheableContract
{
    //
}

其次,为每个实体创建一个存储库(具体实现)

use Rinvex\Repository\Repositories\EloquentRepository;

class UserEloquentRepository extends EloquentRepository implements UserRepositoryContract
{
    //
}

现在在Laravel Service Provider中将它们绑定到IoC(在《register`方法内部)

$this->app->bind(UserRepositoryContract::class, UserEloquentRepository::class)

这样我们就不必手动实例化存储库,并且可以在多个实现之间轻松切换。IoC容器将处理所需的依赖关系。

注意:请参阅Laravel的《Service Providers》和《Service Container》文档以获取更多详细信息。服务提供者服务容器

添加自定义实现

由于我们专注于抽象数据层,并且将抽象接口与具体实现分开,因此很容易添加自己的实现。

例如,如果您的域模型使用网络服务或文件系统数据存储作为其数据源,只需扩展《BaseRepository`类即可,就这么简单。参见

class FilesystemRepository extends BaseRepository
{
    // Implement here all `RepositoryContract` methods that query/persist data to & from filesystem or whatever datastore
}

EloquentRepository触发的事件

存储库在每个动作时触发事件,如《create`、《update`、《delete`。所有触发的事件都以前缀存储库的标识符(在您的《repository`构造函数中设置)开始,如下所示

  • rinvex.repository.uniqueid.entity.created
  • rinvex.repository.uniqueid.entity.updated
  • rinvex.repository.uniqueid.entity.deleted

为了方便起见,以《.entity.created`、《.entity.updated`或《.entity.deleted`结尾的事件具有相应的监听器。通常,我们需要在每次成功操作后刷新缓存(如果启用且存在)。

还有一个事件《rinvex.repository.uniqueid.entity.cache.flushed`,在缓存刷新时触发。默认情况下,它没有监听器,但如果您有模型关系需要执行进一步操作,则可能需要监听它。

强制仓库约定

以下是一些在使用此包时需要了解的重要约定。该包遵循最佳实践,试图使网络工匠的开发更容易,因此它有一些约定来实现标准化和互操作性。

  • 所有触发的事件都有一个唯一的后缀,例如,《.entity.created`。请注意,《.entity.`是自动事件监听器订阅所必需的。

  • 任何使用《Rinvex Repository`的包的默认目录结构如下

├── config                  --> config files
|
├── database
|   ├── factories           --> database factory files
|   ├── migrations          --> database migration files
|   └── seeds               --> database seed files
|
├── resources
|   └── lang
|       └── en              --> English language files
|
├── routes                  --> Routes files
|   ├── api.php
|   ├── console.php
|   └── web.php
|
├── src                     --> self explanatory directories
|   ├── Console
|   |   └── Commands
|   |
|   ├── Http
|   |   ├── Controllers
|   |   ├── Middleware
|   |   └── Requests
|   |
|   ├── Events
|   ├── Exceptions
|   ├── Facades
|   ├── Jobs
|   ├── Listeners
|   ├── Models
|   ├── Overrides
|   ├── Policies
|   ├── Providers
|   ├── Repositories
|   ├── Scopes
|   ├── Support
|   └── Traits
|
└── composer.json           --> composer dependencies file

注意: Rinvex 仓库 遵循 PSR-4:自动加载器 并期望使用它的其他包也遵守相同的规范。这是自动猜测所必需的,例如,当缺少仓库模型时,它会自动猜测并相应地解决,虽然可能不需要完整的目录结构,但这仍是所有 Rinvex 包的标准。

自动猜测

虽然强烈建议明确设置 IoC 容器、仓库标识符和仓库模型;但此包足够智能,可以在缺少这些所需数据时猜测任何数据。

  • IoC 容器 的辅助函数 app() 用于作为未显式提供 IoC 容器实例时的后备。
  • 仓库标识符 建议将仓库标识符设置为点分隔的名称,如 rinvex.repository.uniqueid,但如果它缺失,将使用完全限定的仓库类名(实际上是 get_called_class() 函数的结果)。
  • 仓库模型 通常按照这种方式命名空间仓库,如 Rinvex\Demos\Repositories\ItemRepository,因此相应的模型应按这种方式命名空间,如 Rinvex\Demos\Models\Item。这就是此包在缺少模型时根据默认目录结构猜测模型的方式。

灵活且细粒度的缓存

Rinvex 仓库 拥有一个强大、简单且粒度化的缓存系统,几乎可以处理所有边缘情况。虽然你可以整体启用/禁用应用程序的缓存,但你也可以灵活地为每个单独的查询启用/禁用缓存!这使你有能力排除某些查询的缓存,即使该方法默认情况下或以其他方式被缓存。

让我们看看我们可以控制哪些缓存级别。

整个应用程序缓存

有关详细信息,请参阅 Laravel 的 缓存 文档。

单个查询缓存

按查询更改缓存或禁用它。

// Set cache lifetime for this individual query to 123 minutes
$repository->setCacheLifetime(123);

// Set cache lifetime for this individual query to forever
$repository->setCacheLifetime(-1);

// Disable cache for this individual query
$repository->setCacheLifetime(0);

按查询更改缓存驱动程序。

// Set cache driver for this individual query to redis
$repository->setCacheDriver('redis');

两个 setCacheLifetimesetCacheDriver 方法都是可链式的。

// Change cache lifetime & driver on runtime
$repository->setCacheLifetime(123)->setCacheDriver('redis')->findAll();

// Use default cache lifetime & driver
$repository->findAll();

除非明确禁用,否则默认为所有仓库启用缓存,并保持为你的 rinvex.repository.cache.lifetime 配置值,使用默认应用程序的缓存驱动程序 cache.default(这也可以按查询进行更改)。

是否缓存结果完全取决于你,尽管所有检索 find* 方法默认启用缓存,但你可以为单个查询启用/禁用缓存或控制其缓存方式、缓存时长以及使用的驱动程序。

临时跳过单个HTTP请求缓存

最后,你可以通过在 URL 中传递以下查询字符串来跳过单个请求的缓存:skipCache=true。你可以通过 rinvex.repository.cache.skip_uri 配置选项来修改此参数的名称。

总结

  • 由于这是一个不断发展的实现,它可能根据实际使用情况进行相应的更改。
  • 仓库智能地将缺失的调用方法传递给底层模型,因此你可以通过利用仓库模型实现任何类型的逻辑,甚至复杂的查询。
  • 关于 Active Repository 实现的更多见解,我发布了一篇题为 Active Repository is good & Awesomely Usable 的文章,如果你感兴趣,请阅读。
  • 仓库以非常智能的方式使用缓存标签,即使你选择的缓存驱动程序不支持它。仓库将自行管理它以进行精确的缓存管理。在幕后,它使用 json 文件来存储缓存键。通过检查 rinvex.repository.cache.keys_file 配置选项来更改文件路径。
  • Rinvez 代码库遵循符合PSR-1: 基本编码标准PSR-2: 编码风格指南PSR-4: 自动加载的 FIG PHP 标准建议,以确保共享 PHP 代码之间的高互操作性。
  • 目前,我认为通过实现标准模式来增加一个更复杂的层进行筛选没有带来太多好处,我更愿意保持其现在的简单性,使用传统的 where 子句,因为我们可以达到相同的效果。(你有什么不同的看法?请解释一下)

变更日志

有关项目的完整历史,请参阅变更日志

支持

以下支持渠道随时可供您使用:

贡献与协议

感谢您考虑为这个项目做出贡献!贡献指南可以在CONTRIBUTING.md中找到。

我们非常欢迎错误报告、功能请求和拉取请求。

安全漏洞

如果您在此项目中发现安全漏洞,请发送电子邮件至help@rinvex.com。所有安全漏洞都将得到及时处理。

关于Rinvex

Rinvex 是一家成立于2016年6月的亚历山大市的企业解决方案软件初创公司,专注于为中小企业提供集成解决方案。我们相信,我们的动力在于价值、影响力和影响力,这是我们与众不同的地方,并通过软件的力量释放我们哲学的无限可能性。我们喜欢称之为“以生活速度的创新”。这就是我们为推进人类文明所做的一份贡献。

许可证

本软件在MIT 许可证(MIT)下发布。

(c)2016-2018 Rinvex LLC,部分权利保留。