我正在研究MVC模式以提高我的编码技能,作为练习,我正在编写此路由系统以将动作和参数映射到相对的控制器。我已经测试了代码,并且运行良好,但是我不明白如何将多个参数映射到控制器。这是我的代码,有人可以建议我做一个更好的方法吗?
<?php
if( isset($_SERVER['REQUEST_URI']) ){
$requested_uri = parse_url( $_SERVER['PATH_INFO'], PHP_URL_PATH);
if( $requested_uri === '' ){
echo $controller->index();
}
elseif( $requested_uri != '' ){
$requested_uri = explode('/', $_SERVER['PATH_INFO']);
$class = (string) ucfirst($requested_uri[1]).'Controller';
$method = (string) $requested_uri[2];
if( isset($requested_uri[3]) && class_exists($class) ){
$param = (string) $requested_uri[3];
$obj = new $class;
echo $obj->$method($param);
}
else{
if( class_exists( $class ) ){
$obj = new $class;
echo $obj->$method();
}
}
}
}
?>
答案 0 :(得分:1)
解决方案代码在这里:
<?php
if( isset($_SERVER['REQUEST_URI']) ){
$requested_uri = parse_url( $_SERVER['PATH_INFO'], PHP_URL_PATH);
if( $requested_uri === '' ){
echo $controller->index();
}
elseif( $requested_uri != '' ){
$requested_uri = explode('/', $_SERVER['PATH_INFO']);
$class = (string) ucfirst($requested_uri[1]).'Controller';
$method = (string) $requested_uri[2];
//----- below part is my idea ...
$params = array();
for($i=3 ; $i<=count(requested_uri) ; $i++ ){
$params = requested_uri[$i];
}
$controllerInstance = new $class();
call_user_func_array(array($controllerInstance , $method) , $params);
//---- end part
}
}
?>