Created
September 21, 2016 13:52
-
-
Save bishopb/aff1e84c4528bcdb65610f7695710e42 to your computer and use it in GitHub Desktop.
Fluent Router in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
engine() | |
->if(2)->then(function () { echo 'then'; }) | |
->elif(0)->then() | |
->else() | |
; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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