maartenpaauw / laravel-specification-pattern
这是我包装的laravel-specification-pattern
v2.6.0
2024-09-20 13:34 UTC
Requires
- php: ^8.1
- illuminate/console: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
- spatie/laravel-package-tools: ^1.16.2
- symfony/polyfill-php83: ^1.30
- webmozart/assert: ^1.11
Requires (Dev)
- illuminate/testing: ^10.0|^11.0
- larastan/larastan: ^2.8
- laravel/pint: ^1.0
- nunomaduro/collision: ^7.8|^8.1
- orchestra/testbench: ^8.8|^9.0
- pestphp/pest: ^2.20
- pestphp/pest-plugin-arch: ^2.5
- pestphp/pest-plugin-laravel: ^2.2
- pestphp/pest-plugin-type-coverage: ^2.8
- phpstan/extension-installer: ^1.1
- phpstan/phpstan-deprecation-rules: ^1.0
- phpstan/phpstan-phpunit: ^1.0
- spatie/laravel-ray: ^1.35
- spatie/phpunit-snapshot-assertions: ^5.1
README
使用规范过滤 Illuminate 收集。
支持我
您可以通过购买 Filament 的 Pennant 特性标志来支持我。
安装
您可以通过 composer 安装此包
composer require maartenpaauw/laravel-specification-pattern
您可以使用以下命令发布配置文件
php artisan vendor:publish --tag="laravel-specification-pattern-config"
这是发布配置文件的内容
return [ 'collection-method' => 'matching', ];
用法
以下是创建规范的方法
php artisan make:specification AdultSpecification
这将生成一个位于 App\Specifications
命名空间内的规范类。
<?php namespace App\Specifications; use Maartenpaauw\Specifications\Specification; /** * @implements Specification<mixed> */ class AdultSpecification implements Specification { /** * {@inheritDoc} */ public function isSatisfiedBy(mixed $candidate): bool { return true; } }
假设我们有一个以下类,它表示一个具有给定年龄的人。
class Person { public function __construct(public int $age) {} }
让我们应用业务逻辑
<?php namespace App\Specifications; use Maartenpaauw\Specifications\Specification; /** - * @implements Specification<mixed> + * @implements Specification<Person> */ class AdultSpecification implements Specification { /** * {@inheritDoc} */ public function isSatisfiedBy(mixed $candidate): bool { - return true; + return $candidate->age >= 18; } }
应用业务逻辑后,我们可以通过直接调用 isSatisfiedBy
方法或间接通过调用 matching
方法对 Eloquent 收集进行过滤来使用规范。
直接
$specification = new AdultSpecification(); // ... $specification->isSatisfiedBy(new Person(16)); // false $specification->isSatisfiedBy(new Person(32)); // true
间接
$persons = collect([ new Person(10), new Person(17), new Person(18), new Person(32), ]); // ... // Returns a collection with persons matching the specification $persons = $persons->matching(new AdultSpecification()); // ... $persons->count(); // 2
测试
composer test
变更日志
有关最近更改的更多信息,请参阅变更日志。
贡献
有关详细信息,请参阅贡献指南。
安全漏洞
有关如何报告安全漏洞的信息,请参阅我们的安全策略。
鸣谢
许可协议
MIT 许可协议(MIT)。有关更多信息,请参阅许可文件。