问题总结
我正在制作的 MVC 框架中的路由存在一些小问题。代码看起来应该可以工作,但是我将请求的 uri 拆分为数组并将其分配给字符串变量的方式存在问题。我消除了最初出现的所有错误,所以我继续实例化控制器,这就是我得到的:
错误日志
Class name must be a valid object or a string in /home2/canforce/public_html/index.php on line 23
索引.php
//analyze request
$request = new Request(); //breaks up the uri into an array
//routing
$router = new Router(array($request)); //routes the requested uri
$router->route();
//instancialize and execute the controller
$controller = new $router->getController();
$method = $router->getMethod();
$controller->$method();
请求.php
class Request {
public function __construct() {
//separates the uri into an array
$uri = explode('/',$_SERVER['REQUEST_URI']);
$uri = array_filter($uri);
//stores the requested controller from the uri
if($uri[0]!="") {
$request['controller'] = $uri[0];
}
else {
$request['controller'] = "home";//defaults to home
}
//stores the requested method from the uri
if(isset($uri[1])) {
$request['method'] = $uri[1];
}
else {
$request['method'] = "index";//defaults to index
}
//stores the requested arguments in array form
$count = count($uri);
$j=0;
for($i=2;$i<$count;$i++) {
$request['args'][j] = $request[i];
$j++;
}
return($request);
}
}
路由器.php
class Router {
private $language = NULL;
private $controller;
private $view;
private $method;
private $args = NULL;
public function __construct($request) { //given the requested uri in array form, stores it in local variables
$this->controller = $request['controller'];
$this->method = $request['method'];
$this->args = $request['args'];
}
public function route() { //put the requested uri into forms we can deal with
}
public function getLanguage() {
return $this->language;
}
public function getController() {
return $this->controller;
}
public function getView() {
return $this->view;
}
public function getMethod() {
return $this->method;
}
public function getArgs() {
return $this->args;
}
}
任何帮助表示赞赏!