Skip to content

Instantly share code, notes, and snippets.

@vasildakov-zz
Last active March 15, 2018 15:50
Show Gist options
  • Save vasildakov-zz/56a19cc1cb657826e09808aee8f42145 to your computer and use it in GitHub Desktop.
Save vasildakov-zz/56a19cc1cb657826e09808aee8f42145 to your computer and use it in GitHub Desktop.
Specification Design Pattern
<?php
/**
* class AndX
* @author Vasil Dakov <vasildakov@gmail.com>
*/
class AndX extends CompositeSpecification
{
/**
* @var SpecificationInterface $left
*/
private $left;
/**
* @var SpecificationInterface $right
*/
private $right;
/**
* @param SpecificationInterface $left
* @param SpecificationInterface $right
*/
public function __construct(
SpecificationInterface $left,
SpecificationInterface $right
) {
$this->left = $left;
$this->right = $right;
}
/**
* @param mixed $value
* @return bool
*/
public function isSatisfiedBy($value) : bool
{
return $this->left->isSatisfiedBy($value) && $this->right->isSatisfiedBy($value);
}
}
<?php
/**
* class CompositeSpecification
* @author Vasil Dakov <vasildakov@gmail.com>
*/
abstract class CompositeSpecification implements CompositeSpecificationInterface
{
/**
* @param SpecificationInterface $specification
* @return AndX
*/
public function andX(SpecificationInterface $specification)
{
return new And($this, $specification);
}
/**
* @param SpecificationInterface $specification
* @return OrX
*/
public function orX(SpecificationInterface $specification)
{
return new OrX($this, $specification);
}
}
<?php
/**
* interface CompositeSpecificationInterface
* @author Vasil Dakov <vasildakov@gmail.com>
*/
interface CompositeSpecificationInterface
{
/**
* @param SpecificationInterface $specification
* @return AndX
*/
public function andX(SpecificationInterface $specification);
/**
* @param SpecificationInterface $specification
* @return OrX
*/
public function orX(SpecificationInterface $specification);
}
<?php
/**
* class OrX
* @author Vasil Dakov <vasildakov@gmail.com>
*/
class OrX extends CompositeSpecification
{
/**
* @var SpecificationInterface $left
*/
private $left;
/**
* @var SpecificationInterface $right
*/
private $right;
/**
* @param SpecificationInterface $left
* @param SpecificationInterface $right
*/
public function __construct(SpecificationInterface $left, SpecificationInterface $right)
{
$this->left = $left;
$this->right = $right;
}
/**
* @param mixed $value
* @return bool
*/
public function isSatisfiedBy($value) : bool
{
return $this->left->isSatisfiedBy($value) || $this->right->isSatisfiedBy($value);
}
}
<?php
/**
* interface SpecificationInterface
* @author Vasil Dakov <vasildakov@gmail.com>
*/
interface SpecificationInterface
{
/**
* @param mixed $value
* @return bool
*/
public function isSatisfiedBy($value) : bool;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment