maartenpaauw/laravel-specification-pattern

这是我包装的laravel-specification-pattern

v2.6.0 2024-09-20 13:34 UTC

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Codecov Total Downloads

使用规范过滤 Illuminate 收集。

支持我

Pennant for Filament

您可以通过购买 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)。有关更多信息,请参阅许可文件