- strpos: documentation ( source)
<?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);