- is_callable: documentation ( source)
<?php
interface Router {
public function serve($uri);
}
class FlatRouter implements Router {
public function serve($uri) {
// send()s instance of HTTP\Request, no return value
echo 'Serving request: ', $uri, ' using ', __CLASS__;
}
}
class NestedRouter implements Router {
public function serve($uri) {
// send()s instance of HTTP\Request, no return value
echo 'Serving request: ', $uri, ' using ', __CLASS__;
}
}
abstract class Application {
protected static $instances = array();
private $properties = array();
protected static function getInstance() {
return isset(self::$instances[$className = get_called_class()]) ? self::$instances[$className] : self::$instances[$className] = new static();
}
protected function __construct() {
}
public function __set($propertyName, $value) {
$this->properties[$propertyName] = $value;
}
public function __get($propertyName) {
return is_callable($this->properties[$propertyName]) ? $this->properties[$propertyName] = $this->properties[$propertyName]($this) : $this->properties[$propertyName];
}
}
abstract class WebApplication extends Application {
protected $routerClassName = 'FlatRouter';
protected function __construct() {
$this->router = function ($application) {
$routerClassName = $application->routerClassName;
return new $routerClassName();
};
}
public static function serve($uri) {
$instance = static::getInstance();
$instance->router->serve($uri);
}
}
final class FooBarWebApplication extends WebApplication {
protected $routerClassName = 'NestedRouter';
}
FooBarWebApplication::serve('http://foo.bar/path/to/resource');