Simple PHP Router
A Simple PHP Router to use in your web projects
About
Router Class
Here are some routes i have personally tested
A Simple PHP Router to use in your web projects
About
I created this router for HybridCMS but i felt others should be able to use this router.
If there is issues i might not be able to provide help i am new to regex and i am not sure if this is the most efficient way of doing this.
FeaturesIf there is issues i might not be able to provide help i am new to regex and i am not sure if this is the most efficient way of doing this.
- Static Routing
- When routing to a function in a controller the parameter will be an array
- To specify a string you MUST use [string]
- To specify a integer you MUST use [int]
- Wildcards are not yet supported but will be included soon
PHP:
<?php
require_once( dirname(__FILE__) . '/router.php' );
Router::GET('/', function() {
return require('template/welcome.php');
});
Router::POST('/login', function() {
// handle logig
});
Router::GET('/login', function() {
return require('template/login.php');
});
Router Class
PHP:
<?php
/**
* Simple PHP Router
*
* @author GarettMcCarty <[email protected]> DB:GarettisHere
* @version 1.0.0
* @link http://github.com/GarettMcCarty/HybridCMS
* @license Attribution-NonCommercial 4.0 International
*/
class Router
{
protected static $regex = ['[string]' => '([^/]+)', '[int]' => '(\d+)', '[*]' => '(.*?)'];
protected static $routes = [];
// GET Helper
public static function GET($uri, $callback)
{
return self::addRoute('GET', $uri, $callback);
}
// POST Helper
public static function POST($uri, $callback)
{
return self::addRoute('POST', $uri, $callback);
}
public static function addRoute($method, $uri, $callback)
{
$uri = str_ireplace(array_keys(self::$regex), array_values(self::$regex), $uri);
self::$routes[$uri] = sprintf('~^/index.php%s$~', $uri);
$request = filter_input(INPUT_SERVER, 'REQUEST_URI');
if(strpos($request, 'index.php') == false)
{
$request = sprintf('/index.php%s', $request);
}
if($method != filter_input(INPUT_SERVER, 'REQUEST_METHOD'))
{
return;
}
if(array_key_exists($uri, self::$routes))
{
if(preg_match(self::$routes[$uri], $request, $matches) !== false)
{
if(count($matches) > 0 && $matches[0] == $request)
{
if(is_callable($callback))
{
if(isset($matches[1]))
{
echo $callback($matches[1]);
} else {
echo $callback();
}
} else {
if(stripos($callback, '@'))
{
$data = explode('@', $callback);
$controller = "\application\controller\{$data[0]}";
if(isset($matches[1]))
{
$matches = array_shift($matches);
call_user_func_array(array(new $controller, $data[1]), $matches);
} else {
call_user_func(array(new $controller, $data[1]));
}
} else {
throw new \InvalidArgumentException('Routes must use a controller or a callable function.');
}
}
}
}
}
}
}
Here are some routes i have personally tested
PHP:
Router::GET('/', function()
{
return "Welcome Everyone";
}
Router::GET('/hi/[string]', function($name)
{
return sprintf('Hey %s!', $name);
});
Last edited: