bigpaulie/repository

Laravel 框架的仓库模式实现

v2.0 2020-01-24 11:12 UTC

This package is auto-updated.

Last update: 2024-09-24 21:49:47 UTC


README

Latest Version on Packagist Total Downloads Build Status

Laravel 框架的仓库模式实现

安装

通过 Composer

$ composer require bigpaulie/repository

发布配置文件

$ php artisan vendor:publish --provider=bigpaulie\\repository\\RepositoryServiceProvider --tag=repository.config

兼容性

用法

任何扩展 bigpaulie\repository\AbstractRepository 的类都可以视为一个仓库类。

一般来说,你的仓库应该与你的模型名称相同,后缀为 "Repository"。

假设我们有以下情况,我们有一个名为 Person 的模型,那么仓库类应该命名为 PersonRepository

class PersonRepository extends AbstractRepository {}

使用 artisan 命令生成仓库

你可以使用提供的 artisan 命令为你的模型生成一个仓库

php artisan repository:generate Person

上述命令将生成一个名为 PersonRepository 的仓库类。

查找

通过 ID 查找特定资源

/** @var PersonRepository $repository */
$repository = new PersonRepository();

/** @var Person|null $person */
$person = $repository->find(1);

获取所有

获取此资源的所有结果

/** @var PersonRepository */
$repository = new PersonRepository();

/** @var Illuminate\Database\Eloquent\Collection|Person[] */
$persons = $repository->all();

创建

创建一个新资源并返回数据库对象,如果你的模型不允许批量分配属性,则使用 false 作为第二个参数。

/** @var PersonRepository $repository */
$repository = new PersonRepository();

/** @var Person $person */
$person = $repository->create([
    'name' => 'Popescu Ion',
    'age' => 30
]);

更新

通过 ID 更新特定资源,你也可以通过传递一个模型实例作为第二个参数。

/** @var PersonRepository $repository */
$repository = new PersonRepository();

/** @var Person $person */
$person = $repository->update([
    'name' => 'Popescu Marin',
    'age' => 33
], 1);

删除

通过 ID 删除特定资源,你也可以通过传递 true 作为第二个参数来强制删除。

/** @var PersonRepository $repository */
$repository = new PersonRepository();

try {
    /** @var Person $person */
    $person = $repository->delete(1);
} catch (RepositoryException $exception) {
    // do something if operation fails
}

使用辅助函数

你可以通过提供仓库或模型的完全限定名(FQDN)来使用辅助函数。

如果给定的模型存在仓库,将返回仓库的实例;否则,将返回一个抽象仓库,允许你执行所有内置的 CRUD 功能。

Person 模型有一个 PersonRepository

/** @var PersonRepository $person */
$personRepository = repository(PersonRepository::class);

/** @var PersonRepository $person */
$personRepository = repository(Person::class);

Dog 模型没有仓库

/** @var bigpaulie\repository\Repository $dog */
$repository = repository(Dog::class);

了解更多

查看我们的 wiki

变更日志

请参阅 changelog 以获取最近更改的更多信息。

测试

$ ./vendor/bin/phpunit -c phpunit.xml

贡献

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

安全性

如果您发现任何安全相关的问题,请通过作者邮箱而不是使用问题跟踪器。

鸣谢

许可

许可。请参阅 许可文件 以获取更多信息。