boulzy / specification
PHP implementation of the Specification pattern.
Requires
- php: ^8.2
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.37
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.4
- symfony/var-dumper: ^6.3
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
PHP library implementing the Specification pattern.
Installation
The preferred method of installation is via Composer. Run the following command to install the package and add it as a requirement to your project's composer.json:
$ composer require boulzy/specification
Usage
The design pattern "Specification" describes business rules. Specifications can be chained or combined to apply more complex business rules.
A Specification must implement the interface Boulzy\Specification\Specification, though it's recommanded to
extend the abstract class Boulzy\Specification\CompositeSpecification that already implements the combination of
specifications.
<?php
class TrueSpecification extends Boulzy\Specification\CompositeSpecification
{
public function isSatisfiedBy($candidate) : bool
{
return true === $candidate;
}
}
class FalseSpecification extends Boulzy\Specification\CompositeSpecification
{
public function isSatisfiedBy($candidate) : bool
{
return false === $candidate;
}
}
$trueSpecification = new TrueSpecification();
$falseSpecification = new FalseSpecification();
$isSatisfied = $trueSpecification->isSatisfiedBy(true); // true
$isSatisfied = $trueSpecification->isSatisfiedBy(false); // false
$isSatisfied = $falseSpecification->isSatisfiedBy(true); // false
$isSatisfied = $falseSpecification->isSatisfiedBy(false); // true
$isSatisfied = $trueSpecification->not()->isSatisfiedBy(true); // false
$isSatisfied = $trueSpecification->not()->isSatisfiedBy(false); // true
$isSatisfied = $trueSpecification->and($falseSpecification)->isSatisfiedBy(true); // false
$isSatisfied = $trueSpecification->and($falseSpecification)->isSatisfiedBy(false); // false
$isSatisfied = $trueSpecification->andNot($falseSpecification)->isSatisfiedBy(true); // true
$isSatisfied = $trueSpecification->or($falseSpecification)->isSatisfiedBy(true); // true
See the unit tests for simple examples.
License
This project is licensed under the MIT License.