Skip to content

Instantly share code, notes, and snippets.

@bishopb
Created September 21, 2016 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bishopb/aff1e84c4528bcdb65610f7695710e42 to your computer and use it in GitHub Desktop.
Save bishopb/aff1e84c4528bcdb65610f7695710e42 to your computer and use it in GitHub Desktop.
Fluent Router in PHP
engine()
->if(2)->then(function () { echo 'then'; })
->elif(0)->then()
->else()
;
function engine() {
$engine = new FluentRouter;
$then = function ($callable) use ($engine) {
$callable();
return $engine;
};
$if = function ($condition) use (&$if, $then) {
$router = new FluentRouter;
if ($condition) {
$router->addCallback('then', $then);
} else {
$router->addCallback('elif', $if);
$router->addCallback('else', $then);
}
return $router;
};
$engine->addCallback('if', $if);
return $engine;
}
<?php
class FluentRouter
{
const DEADEND_EXCEPTION = 1;
const DEADEND_RETRY = 2;
const DEADEND_BLACKHOLE = 3;
public function __construct(array $callbacks = [], $deadend = null)
{
$this->callbacks = $callbacks;
$this->deadend = $deadend;
}
public function addCallback($method, callable $callback)
{
$this->callbacks[$method] = $callback;
}
public function removeCallback($method)
{
unset($this->callbacks[$method]);
}
public function __call($method, $arguments)
{
if (array_key_exists($method, $this->callbacks)) {
$callback = $this->callbacks[$method];
return $callback(...$arguments);
} else {
switch ($this->deadend) {
case static::DEADEND_EXCEPTION:
throw new \BadMethodException($method);
case static::DEADEND_BLACKHOLE:
return new static;
case static::DEADEND_RETRY:
default:
return $this;
}
}
}
}
// PROTECTED API
protected $callbacks;
protected $deadend;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment