yusukezzz / routing
PHP 的简单快速请求路由器
dev-master
2015-03-16 04:46 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: 4.*
This package is not auto-updated.
Last update: 2024-09-18 08:09:53 UTC
README
此库是从 nikic/FastRoute 分支出来的。
非常感谢 nikic 和 FastRoute 的其他贡献者。
安装
在您的 composer.json 中要求此包
"yusukezzz/routing": "dev-master"
使用方法
<?php require_once __DIR__ . '/path/to/vendor/autoload.php'; $router = new \yusukezzz\Routing\Router(); $router->get('/', function() { return 'Hello world.'; }); $router->get('/user/:name', function($name) { return "Hello {$name}"; }); echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);
在 PHP 内置服务器中运行
php -S localhost:8080 router.php
反向路由
// set third parameter to define named route $router->get('/hoge/:piyo', function($piyo){}, 'a_named_route'); echo $router->urlFor('a_named_route', ['piyo' => 'abc']); // output is '/hoge/abc'
如果您想使用类似于路由的控制器,您应该实现 RouteHandlerInterface。
<?php require_once __DIR__ . '/../vendor/autoload.php'; class PhotoController { public function index() { return 'photo list'; } public function show($id) { return "show photo id {$id}"; } } class Handler implements \yusukezzz\Routing\RouteHandlerInterface { /** * @param \yusukezzz\Routing\Route $route * @return mixed */ public function handleRoute(\yusukezzz\Routing\Route $route) { list($controller, $method) = explode('@', $route->getHandler()); $handler = [new $controller, $method]; return call_user_func_array($handler, $route->getVariables()); } } $handler = new \Handler(); $router = new \yusukezzz\Routing\Router($handler); $router->get('/photo', 'PhotoController@index'); $router->get('/photo/:id', 'PhotoController@show'); echo $router->handle($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);