
<?php
//Handler
abstract class Rescuer {
protected $next = null;
public $code = 0;
//HandleRequest()
function help(int $code) {
if ($this->code == $code) {
$this->toHelp();
} else if ($this->next != null) {
$this->next->help($code);
}
}
abstract function toHelp();
}
//ConcreteHandler
class Firefighter extends Rescuer {
function __construct($next) {
$this->next = $next;
$this->code = 1;
}
function toHelp() {
echo "call firefighters", "\n";
}
}
//ConcreteHandler
class Police extends Rescuer {
function __construct($next) {
$this->next = $next;
$this->code = 2;
}
function toHelp() {
echo "call the police", "\n";
}
}
//ConcreteHandler
class Ambulance extends Rescuer {
function __construct($next) {
$this->next = $next;
$this->code = 3;
}
function toHelp() {
echo "call an ambulance", "\n";
}
}
$ambulance = new Ambulance(null);
$police = new Police($ambulance);
$firefighter = new Firefighter($police);
$firefighter->help(1);
//printed: call firefighters
$firefighter->help(2);
//printed: call the police
$firefighter->help(3);
//printed: call an ambulance
| Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it. |