superatom / routing
The Superatom Routing package.
dev-master
2015-08-16 15:09 UTC
Requires
- php: >5.6.0
- nikic/fast-route: ^0.6
- symfony/http-foundation: ~2.0
Requires (Dev)
- fabpot/php-cs-fixer: ~1.0
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-10-28 04:51:34 UTC
README
This library provides a regular expression based fast routing.
Acknowledgment
Original regex matching implementation by nikic/FastRoute.
Very thanks to nikic and other contributors.
Install
Require this package in your composer.json
"superatom/routing": "1.*"
Usage
Hello world example
<?php
require_once '/path/to/vendor/autoload.php';
$handler = new \Superatom\Routing\RouteHandler();
$generator = new \Superatom\Routing\RouteDataGenerator();
$router = new \Superatom\Routing\Router($handler, $generator);
$router->get('/', function()
{
return 'Hello world!';
});
echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
Save as hello.php
And run in terminal php -S localhost:8080 hello.php
Open localhost:8080/ in browser.
Route with parameter
$router->get('/hello/:name', function($name)
{
return "Hello {$name}!";
}, $name_for_this_route = 'hello');
Open localhost:8080/hello/atom in browser.
Reverse routing
$router->get('/:var1/:var2', function($var1, $var2)
{
return "got {$var1} and {$var2}";
}, 'route1');
echo $router->urlFor('route1', ['var1' => 'hoge', 'var2' => 'piyo']);
Custom route handler
use \Superatom\Routing\Route;
class ControllerHandler implements \Superatom\Routing\RouteHandlerInterface
{
/**
* @param Route $route
* @return mixed
*/
public function handleRoute(Route $route)
{
list($class, $method) = explode('@', $route->getHandler());
$controller = new $class();
// controller setup...
// e.g. Dependency injection
$handler = [$controller, $method];
return call_user_func_array($handler, $route->getVariables());
}
}
class HelloController
{
public function greeting($name)
{
return "Hello {$name}!";
}
}
$handler = new ControllerHandler();
$generator = new \Superatom\Routing\RouteDataGenerator();
$router = new \Superatom\Routing\Router($handler, $generator);
$router->get('/hello/:name', 'HelloController@greeting');
echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
Open localhost:8080/hello/atom in browser.
License
MIT