Last active
July 19, 2018 02:32
-
-
Save jaceju/a7267159ffd3b1c1785e40d28ff4e5b3 to your computer and use it in GitHub Desktop.
Chain of Responsibility Pattern Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
return AbstractStep::registerSteps([ | |
new Step1, | |
new Step2, | |
new Step3, | |
])->handle($data); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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