Skip to content

Instantly share code, notes, and snippets.

@jaceju jaceju/AbstractStep.php
Last active Jul 19, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.