brenoroosevelt / php-specifications
PHP 中规范模式的实现
dev-main
2021-10-15 13:50 UTC
Requires
- php: >=7.1
- respect/validation: ^2
Requires (Dev)
- phpstan/phpstan: ^0.12.90
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: 3.5.*
This package is auto-updated.
Last update: 2024-09-15 20:05:58 UTC
README
在 PHP 中实现通用目的的规范模式。
要求
- PHP >= 7.1
安装
composer require brenoroosevelt/php-specifications
定义
规范是实现了 Specification
接口的类
<?php declare(strict_types=1); namespace BrenoRoosevelt\Specification; interface Specification { public function isSatisfiedBy($candidate): bool; }
约束
以下函数使用以下规范评估候选者
运算符
链式规范
可以使用以下函数链式组合规范
链式规范将使用相应的运算符进行评估。
可迭代对象的横向规范
通常与集合一起使用,这些特殊规范迭代候选者并评估其元素。
选择器
这些特殊规范提取候选值,然后评估规范。
创建规范
<?php class RecentUser implements Specification { private $daysAgo; public function __construct(int $daysAgo = 15) { $this->daysAgo = $daysAgo; } public function isSatisfiedBy($candidate): bool { $daysAgo = (new DateTimeImmutable())->modify(sprintf("-%s days", $this->daysAgo)); return $candidate instanceof User && $candidate->createdAt() >= $daysAgo; } }
<?php $user = new User(/** ... */); (new RecentUser(30))->isSatisfiedBy($user); // (bool) rule(RecentUser::class, 30)->isSatisfiedBy($user); // (bool) anyOf()->rule(RecentUser::class)->method('getCategory', in(['premium']))->isSatisfiedBy($user); // (bool)
内联规范
<?php rule(fn($candidate) => $candidate->isActive());