Download the PHP package bentools/specification without Composer
On this page you can find all versions of the php package bentools/specification. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download bentools/specification
More information about bentools/specification
Files in bentools/specification
Package specification
Short Description Provides an implementation of the Specification Pattern. PHP7+
License MIT
Informations about the package specification
bentools/specification
PHP7.1+ implementation of the Specification Pattern.
The goal
The Specification Pattern allows you to wrap some conditionnal structures into value objects. This may have no sense in your usual code, but it can be useful when the combination of your business rules reaches a high Cyclomatic Complexity.
Thus, wrapping your conditions into named objects with a specific failure handling may help you to:
- Add new business rules to existing ones
- Have a better understanding of your conditionnal structures
- Find which condition invalidates the others
- Avoid unreadable lasagna-code
The principles of the Specification Pattern are borrowed from Domain Driven Design, but can be applied anywhere.
Overview
A specification is a kind of enhanced conditionnal structure, which can be chained to other specifications.
Here's how to create a specification:
As you can see, the validate()
method is used to validate a specification is met. It returns void
(nothing).
When a specification is unmet, the validate()
method throws an UnmetSpecificationException
:
When handling these exceptions, you can know which specification(s) failed. To identify them, you can name each specification:
Specification quick check
Instead of dealing with try/catch blocks, you can check wether or not a specification is met by calling $spec->isSatisfied()
, which will handle this for you and return a boolean.
Create specifications
The spec()
, group()
and not()
functions, and the and()
and or()
methods are Specification factories, that will return a Specification
object. They accept as an argument:
- A boolean
- A callable that will resolve to a boolean
- An existing
Specification object
Examples:
Group and Chain specifications
A Specification
object contains and
and or
methods that can be used to create composite specifications. You can also use the group()
function which will behave like parenthesis:
Create your own specifications
Since the Specification Pattern is intended to test your business rules, you can extend the abstract Specification
class to create your own objects instead of relying on simple booleans:
Advanced Example
Since the Specification Pattern is intended to test your business rules, you should better implement your own Specification
classes.
See our example to get started.
Installation
License
MIT