【问题标题】:AltoRouter - mapping/routing home class as defaultAltoRouter - 默认映射/路由主类
【发布时间】:2017-12-26 14:00:48
【问题描述】:
我知道你如何称呼你的控制器here,但是如何在AltoRouter中将'Home'设置为默认控制器和'index'作为默认操作
这是错误的,但类似
$router->map('GET', '/', function($controller, $action) {
$controller = 'Home';
$action = 'index';
});
【问题讨论】:
标签:
php
model-view-controller
routing
altorouter
【解决方案1】:
取决于你所说的“默认操作”是什么意思。
如果您的意思是“我如何使'/' 路由转到我的index() 类的index() 方法”,那么链接的github 问题(和the AltoRouter website)的简化版本将适用:
$router = new AltoRouter();
$router->setBasePath('/example.com');
$router->map('GET','/', 'HomeController#index');
$match = $router->match();
if ($match === false) {
header($_SERVER["SERVER_PROTOCOL"].' 404 Not Found');
} else {
list($controller, $action) = explode('#', $match['target']);
if ( is_callable([$controller, $action]) ) {
$obj = new $controller();
call_user_func_array([$obj, $action], [$match['params']]);
} else {
// here your routes are wrong.
// Throw an exception in debug, send a 500 error in production
}
}
这里的# 完全是任意的,它只是将控制器名称与被调用的方法分开的分隔符。 laravel 使用@ 表示类似的路由器到控制器表示法(即HomeController@index)。
如果您的意思是“如果有疑问,将主页显示为默认操作”,那么它看起来与上面非常相似,唯一的区别是 404 路径将是:
if ($match === false) {
$obj = new HomeController();
$obj->index();
} else {
// etc.
}