sidvind / php-routes
为 PHP 项目提供路由功能
v1.6.1
2023-03-25 15:21 UTC
Requires
- php: ^8.1 || ^8.2
Requires (Dev)
- php-coveralls/php-coveralls: 2.5.3
- phpunit/phpunit: 9.6.5
- squizlabs/php_codesniffer: 3.7.2
- dev-master
- v1.6.1
- v1.6.0
- v1.5.0
- v1.4.2
- v1.4.1
- v1.4.0
- v1.3.0
- v1.2.7
- v1.2.5
- v1.2.4
- v1.2.3
- v1.2.2
- v1.2.1
- v1.2.0
- v1.1.0
- v1.0.0
- dev-renovate/phpunit-phpunit-11.x
- dev-renovate/actions-cache-4.x
- dev-renovate/phpunit-phpunit-9.x
- dev-renovate/squizlabs-php_codesniffer-3.x
- dev-feature/chores
- dev-feature/readthedocs2
This package is auto-updated.
Last update: 2024-09-20 15:27:33 UTC
README
为 MVC 风格的 PHP 项目提供路由。
composer require sidvind/php-routes
示例
将路由放在单独的文件中,例如 routes.php
<?php /* basic routes */ $get('foo', ['to' => 'MyController#foo']); $post('bar/:id/baz', ['to' => 'MyController#update']); /* use :var for variables */ /* automatically setup RESTful routes */ $resource('article', [], function($r){ $r->members(function($r){ $r->patch('frobnicate'); /* maps to PATCH /article/:id/frobnicate */ }); $r->collection(function($r){ $r->patch('twiddle'); /* maps to PATCH /article/twiddle */ }); }); /* scoping */ $scope(':lang', [], function($r){ $r->get('barney'); /* maps to GET /:lang/barney */ });
创建一个分发器
<?php class Dispatcher extends Sidvind\PHPRoutes\Router { public function dispatch($url, $method){ if ( $match = $this->match($url, $method) ){ $class = "{$match->controller}Controller"; $controller = new $class(); return call_user_func_array([$controller, $match->action], $match->args); } else { /* 404 */ } } } $router = new Dispatcher('routes.php'); $router->dispatch($url, $method);
要预览/调试路由,请使用 bin/php-routes
# bin/php-routes routes.php
GET /foo MyController#foo #^/foo(?P<format>\.\w+)?$#
POST /bar/:id/baz MyController#update #^/bar/(?P<id>[A-Za-z0-9\-_\.]+)/baz(?P<format>\.\w+)?$#
article GET /article Article#list #^/article(?P<format>\.\w+)?$#
...
# bin/php-routes routes.php get /foo
Controller: MyController
Action: foo
Format:
Arguments:
[]
# bin/php-routes routes.php get /bar
bin/php-routes: url doesn't match any route.