Skip to content

Instantly share code, notes, and snippets.

@unclexo
Created February 22, 2023 17:27
Show Gist options
  • Save unclexo/b08bd46da3951cc351e6a8ff52721902 to your computer and use it in GitHub Desktop.
Save unclexo/b08bd46da3951cc351e6a8ff52721902 to your computer and use it in GitHub Desktop.
Chain of Responsibility pattern PHP code example
<?php
class Job {
private $details;
public function __construct($details) {
$this->details = $details;
}
public function requirements() {
return $this->details;
}
}
class StackDetector {
public static function match($stack, $details) {
return strpos($details, $stack) !== false;
}
}
abstract class Handler {
protected $successor;
public function forwardToSuccessor($job) {
if ($this->successor) {
$this->successor->handle($job);
}
}
abstract public function handle($job);
}
class PHPStack extends Handler {
public function __construct($successor) {
$this->successor = $successor;
}
public function handle($job) {
if (StackDetector::match('PHP', $job->requirements())) {
// Notify PHP developers
echo 'PHP Stack';
} else {
$this->forwardToSuccessor($job);
}
}
}
class JavaScriptStack extends Handler {
public function __construct($successor) {
$this->successor = $successor;
}
public function handle($job) {
if (StackDetector::match('JavaScript', $job->requirements())) {
// Notify JavaScript developers
echo 'JavaScript Stack';
} else {
$this->forwardToSuccessor($job);
}
}
}
class JavaStack extends Handler {
public function __construct($successor) {
$this->successor = $successor;
}
public function handle($job) {
if (StackDetector::match('Java', $job->requirements())) {
// Notify Java developers
echo 'Java Stack';
} else {
$this->forwardToSuccessor($job);
}
}
}
class DoNothing extends Handler {
public function handle($job) {
// Do nothing
echo 'The request object is unhandled';
}
}
// Chain of Job handler objects
$doNothing = new DoNothing();
$javaStack = new JavaStack($doNothing);
$javaScriptStack = new JavaScriptStack($javaStack);
$phpStack = new PHPStack($javaScriptStack);
// The request object to be handled
$job = new Job('PHP'); // Try changing the value to Python, JavaScript or Java
// Starts handling the Job object
$phpStack->handle($job);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment