boulzy/specification

PHP implementation of the Specification pattern.

1.2.1 2023-11-01 12:52 UTC

This package is auto-updated.

Last update: 2024-10-30 01:54:16 UTC


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.