Skip to content

Instantly share code, notes, and snippets.

@jaceju
Last active July 19, 2018 02:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaceju/a7267159ffd3b1c1785e40d28ff4e5b3 to your computer and use it in GitHub Desktop.
Save jaceju/a7267159ffd3b1c1785e40d28ff4e5b3 to your computer and use it in GitHub Desktop.
Chain of Responsibility Pattern Example
<?php
abstract class AbstractStep
{
protected $successor;
protected $shouldPassToSuccessor = true;
public static function registerSteps(array $steps): AbstractStep
{
$firstStep = $nextStep = array_shift($steps);
foreach ($steps as $step) {
$nextStep = $nextStep->next($step);
}
return $firstStep;
}
public function next(AbstractStep $step): AbstractStep
{
$this->successor = $step;
return $step;
}
public function handle($data)
{
$data = $this->process($data);
if ($this->shouldPassToSuccessor && $this->successor) {
$data = $this->successor->handle($data);
}
return $data;
}
abstract protected function process($data);
}
<?php
return AbstractStep::registerSteps([
new Step1,
new Step2,
new Step3,
])->handle($data);
<?php
class Step1 extends AbstractStep
{
protected function process($data)
{
$this->shouldPassToSuccessor = $this->check($data);
return $data;
}
private function check($data)
{
// return true or false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment