iextra / router
router
dev-master
2020-06-21 19:19 UTC
Requires
- php: >=7.1
Requires (Dev)
- iextra/dumper: ^1.0
- phpunit/phpunit: ^9.2
This package is auto-updated.
Last update: 2024-09-22 04:52:31 UTC
README
添加路由
路由需要两个参数。
第一个是URL模式。第二个是'操作'(要执行的操作)
use Extra\Routing\Route; Route::get('/', function(){ return 'Hello World'; });
可用于添加路由的方法
use Extra\Routing\Route; Route::any('/', 'action'); Route::get('/news', 'action'); Route::post('/news/{id}', 'action'); Route::put('/news/{id}', 'action'); Route::delete('/news/{id}', 'action'); Route::some(['head', 'options', 'connect', 'trace', 'patch'], '/test', 'action');
路由可用的'操作'
use Extra\Routing\Route; // Function name Route::get('/', 'FunctionName'); // The class name and method name are specified through the @ separator Route::get('/', 'ClassName@method'); // Callback function Route::get('/', function(){ return 'Hello World'; });
搜索并执行匹配的路由
use Extra\Routing\Router; try { $router = Router::getInstance()->includeRoutesFile('path_to_file_with_routes.php'); $route = $router->match($requestUri, $requestMethod); $result = $route->execute($requestUri); } catch (\Exception $e){ die($e->getMessage()); }
执行路由
为了将参数传递给函数,
需要函数接受的变量名与URL中指示的名称相同
在 {id}
use Extra\Routing\Router; $route = Route::get('/news/{id}', function($id){ return 'Id of the news: ' . $id; }); $requestUrl = '/post/86'; $result = $route->execute($requestUrl); echo $result; // 'Id of post: 86'
设置路由名称
use Extra\Routing\Route; Route::get('/news/', 'NewsController@list')->name('news.list'); Route::get('/news/{id}', 'NewsController@detail')->name('news.detail');
设置路由规则
use Extra\Routing\Route; // One rule Route::delete('/news/{id}', 'NewsController@delete')->rule('id', '[0-9]+'); // Few rules Route::post('/catalog/{section}/{id}', 'CatalogController@detail')->rules([ 'section' => '(cars|motorbikes)', 'id' => '\d+' ]); // To indicate that the parameter is optional, // you need to put a question mark in front of it {?page} Route::get('/news/{section}/{?page}', function($section, $page = 1){ return 'Section: ' . $section . ' | Page: ' . $page; });
按名称搜索路由
use Extra\Routing\Router; $router = Router::getInstance(); $route = $router->getRouteByName('news.list');
生成路由URL
use Extra\Routing\Router; use Extra\Routing\Route; $router = Router::getInstance(); Route::get('/news/{id}', 'action')->name('news.detail'); // Way 1 (using router) $url = $router->generateRouteUrl('news.detail', ['id' => 86]); // Way 2 (using route) $route = $router->getRouteByName('news.detail'); $url = $route->generateUrl(['id' => 86]); echo $url; // '/news/86';