admirhodzic / nano-router
PHP应用的Nano路由器
1.0.0
2019-11-01 07:50 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ^8
This package is auto-updated.
Last update: 2024-09-06 20:45:00 UTC
README
Nano-size路由器,仅用20行代码实现PHP应用的路由。
安装
composer require admirhodzic/nano-router
用法
use admirhodzic\NanoRouter\NanoRouter;
// ...
$response = NanoRouter::run([
//options...
]);
当请求URL为 /posts/update/123?param2=abc 时,此代码将调用名为PostController的类,并调用名为 actionUpdate 的方法,将 $id 参数设置为 '123',将 'param2' 设置为 'abc'。如果param2未设置,则使用默认值。"id" 参数是必需的。
class PostController{
public action actionUpdate($id, $param2=''){ ... }
}
如果URL不包含控制器或操作名称,则将使用默认值。默认情况下,使用'SiteController'和'actionIndex'方法。要为不同的HTTP方法指定不同的方法,只需添加一个具有方法名称的函数而不是'actions'即可。
public function getPosts() { ... }
public function postPosts() { ... }
public function actionPosts() { ... }
这样,对于GET请求,将调用'getPosts'函数,对于POST请求,将调用'postPosts'函数,对于所有其他请求方法,将调用'actionsPosts'。
选项
'default_controller'=>'site',
'default_action'=>'index',
'Controller'=>'Controller', //suffix of controller class name
'controller_namespace'=>'app\Controllers',
'routes'=>[
//...custom routes. eg:
'/login'=>'site/login',
/////////////// value is new URI string or a function which receives preg matches and returns a string
'r1/a1(/(?<id>[0-9]*))?'=>function ($p) { ///////////// this matches r1/ar with optional numeric id
//function receives extracted parameters and returns new <controller>/<action>/<id> URI
return isset($p['id']) ? ('site/other/'.$p['id']) : 'site/index';
},
/////////////// routes order must be from most specific to general routes
]
许可证
MIT