2013-02-18 03:48:21 +01:00
|
|
|
<?php
|
|
|
|
|
2015-08-29 03:34:34 +02:00
|
|
|
namespace Router;
|
2013-02-18 03:48:21 +01:00
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Load controllers: bootstrap('controllers', 'controller1', 'controller2')
|
|
|
|
function bootstrap()
|
|
|
|
{
|
|
|
|
$files = \func_get_args();
|
|
|
|
$base_path = array_shift($files);
|
|
|
|
|
|
|
|
foreach ($files as $file) {
|
|
|
|
require $base_path.'/'.$file.'.php';
|
|
|
|
}
|
|
|
|
}
|
2013-02-18 03:48:21 +01:00
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Execute a callback before each action
|
2013-02-18 03:48:21 +01:00
|
|
|
function before($value = null)
|
|
|
|
{
|
|
|
|
static $before_callback = null;
|
|
|
|
|
|
|
|
if (is_callable($value)) {
|
|
|
|
$before_callback = $value;
|
2016-04-18 01:44:45 +02:00
|
|
|
} elseif (is_callable($before_callback)) {
|
2013-02-18 03:48:21 +01:00
|
|
|
$before_callback($value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Execute a callback before a specific action
|
|
|
|
function before_action($name, $value = null)
|
|
|
|
{
|
|
|
|
static $callbacks = array();
|
2013-02-18 03:48:21 +01:00
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
if (is_callable($value)) {
|
|
|
|
$callbacks[$name] = $value;
|
2016-04-18 01:44:45 +02:00
|
|
|
} elseif (isset($callbacks[$name]) && is_callable($callbacks[$name])) {
|
2014-02-08 20:13:14 +01:00
|
|
|
$callbacks[$name]($value);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Execute an action
|
2014-02-09 21:13:36 +01:00
|
|
|
function action($name, \Closure $callback)
|
2013-02-18 03:48:21 +01:00
|
|
|
{
|
|
|
|
$handler = isset($_GET['action']) ? $_GET['action'] : 'default';
|
|
|
|
|
|
|
|
if ($handler === $name) {
|
2014-02-08 20:13:14 +01:00
|
|
|
before($name);
|
|
|
|
before_action($name);
|
2013-02-18 03:48:21 +01:00
|
|
|
$callback();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Execute an action only for POST requests
|
2014-02-09 21:13:36 +01:00
|
|
|
function post_action($name, \Closure $callback)
|
2013-02-18 03:48:21 +01:00
|
|
|
{
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
|
|
action($name, $callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Execute an action only for GET requests
|
2014-02-09 21:13:36 +01:00
|
|
|
function get_action($name, \Closure $callback)
|
2013-02-18 03:48:21 +01:00
|
|
|
{
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
|
|
|
|
action($name, $callback);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-02-08 20:13:14 +01:00
|
|
|
// Run when no action have been executed before
|
2014-02-09 21:13:36 +01:00
|
|
|
function notfound(\Closure $callback)
|
2013-02-18 03:48:21 +01:00
|
|
|
{
|
2014-02-08 20:13:14 +01:00
|
|
|
before('notfound');
|
|
|
|
before_action('notfound');
|
2013-02-18 03:48:21 +01:00
|
|
|
$callback();
|
|
|
|
}
|