onesimus-systems / osrouter
一款简单易用的PHP Web应用路由器
Requires (Dev)
- phpunit/phpunit: 9.1.*
README
OSRouter 是一个简单快速的PHP HTTP路由器。它可以执行带有变量和可选URL部分的简单路由。OSRouter 可以将URL的某些部分作为变量提取出来,传递给闭包或控制器方法。
需求
- PHP >= 5.4.0
用法
use \Onesimus\Router\Router; use \Onesimus\Router\Http\Request; // First we add some routes // The root path is sent to the index method of the HomeController class Router::get('/', 'HomeController@index'); // Any path with a page such as /dash, /admin, etc Router::get('/{page}', 'RenderController@render'); // API, required module, optional method // Executes the closure Router::post('/api/{module}/{?method}', function() { // Closure for route return; }); // Match rest of URL Router::get('/api/{*rest}', 'ApiController@serve'); // Get request object for current HTTP request $request = Request::getRequest(); // Get the matching route for the given request $route = Router::route($request); // Dispatch route // Execute the closure or the class/method combo $route->dispatch(); // You can also pass an argument to the called closure // or the class being instantiated $route->dispatch($app);
主要方法有 Router::get()
、::post()
和 ::any()
。每个方法的签名是 ($pattern, $callback, $options = [])
。$pattern 是路由将匹配的URI模式,格式为 /static/{variable}/{?option-variable}
。$callback 是一个字符串,如 Controller@method
,或者是一个闭包函数。$options 可以是一个字符串,在这种情况下,它将被解释为一个单独的过滤器,或者它可以是具有语法 ['filter' => ['filter1', 'filter2']]
的数组。外层数组允许添加以后可能添加的额外选项。
如果您要在位于Web服务器子目录中的应用程序中路由,您需要从请求对象中的 REQUEST_URI 字段中删除目录前缀。例如,如果您的应用程序的基本位置在 http://example.com/blog
,您需要在处理路由之前从请求URI中删除 "/blog"。否则,所有路由都将与 "/blog/something" 而不是 "/something" 进行检查。
您还可以在组中注册路由
Router::group(['prefix' => '/admin'], ['get', '/groups/{?id}', 'Controller@groups'], ['get', '/users/{?id}', 'Controller@user'] );
组使用 Router::group(array $options, array $routes)
方法定义。$options 是一个键值数组,键为 'filter'、'prefix' 和 'rprefix'。'Filter' 是应用于组的过滤器数组。也可以将单个过滤器作为字符串提供。'Prefix' 是添加到每个组中HTTP模式的前缀。在上面的示例中,路由将是 /admin/groups/{?id}
和 /admin/users/{?id}
。'Rprefix' 是添加到每个控制器语句的前缀。例如,如果在上面的组中添加了 'rprefix' => '\Namespace\Admin\'
,则控制器语句将是 \Namespace\Admin\Controller@groups
和 \Namespace\Admin\Controller@user
。
注意:闭包不能分配给在组中定义的路由。要分配闭包,请单独分配路由。
您可以使用方法 Router::register404Route($callback, $options = [])
定义404路由。如果没有定义404路由并且找不到路由,将抛出 RouteException
。
过滤器
可以定义和分配过滤器到路由。路由可以有多个过滤器,它们将按照在路由中定义的顺序处理。如果所有过滤器都返回非假值,则路由将被绿灯放行,并将继续执行分发。否则将抛出 FailedFilterException
。此外,如果过滤器未定义,将抛出 RouteException
。
示例
// First register filter // This function will return true if the session is authenticated // or false otherwise. You may want to do some sort of redirect here // as well for a failed authentication for example to a login page. Router::filter('auth', function() { return is_authenticated(); }); // Define route for '/admin' path with filter of 'auth' Router::get('/admin', 'AdminController@index', 'auth');
当派发上述路由时,将执行 'auth' 过滤器,如果它返回非假值,则正常将控制权交给 AdminController。您可以使用数组定义多个过滤器。
Router::get('/admin', 'AdminController@index', ['auth', 'inAdminGroup']);
在这种情况下,两个过滤器都必须返回真值。