我正在尝试将自动加载器添加到我的 MVC 的加载器中,以消除对需求和包含的所有需求。
自动加载器可以工作,因为我以前用过它。
我需要知道的是如何更新此代码以删除所有不需要的“要求”。
我认为需要更改的部分就在 createController() 方法中,它检查控制器类文件是否存在
<?php
class Loader {
private $controllerName;
private $controllerClass;
private $action;
private $urlValues;
//store the URL request values on object creation
public function __construct() {
$this->urlValues = $_GET;
if ($this->urlValues['controller'] == "") {
$this->controllerName = "home";
$this->controllerClass = "HomeController";
} else {
$this->controllerName = strtolower($this->urlValues['controller']);
$this->controllerClass = ucfirst(strtolower($this->urlValues['controller'])) . "Controller";
}
if ($this->urlValues['action'] == "") {
$this->action = "index";
} else {
$this->action = $this->urlValues['action'];
}
}
//factory method which establishes the requested controller as an object
public function createController() {
//check our requested controller's class file exists and require it if so
if (!file_exists("controllers/class." . $this->controllerName . ".php")) {
require("controllers/class." . $this->controllerName . ".php");
} else {
require("controllers/class.error.php");
return new ErrorController("badurl",$this->urlValues);
}
//does the class exist?
if (class_exists($this->controllerClass)) {
$parents = class_parents($this->controllerClass);
//does the class inherit from the BaseController class?
if (in_array("BaseController",$parents)) {
//does the requested class contain the requested action as a method?
if (method_exists($this->controllerClass,$this->action))
{
return new $this->controllerClass($this->action,$this->urlValues);
} else {
//bad action/method error
//require("controllers/error.php");
return new ErrorController("badurl",$this->urlValues);
}
} else {
//bad controller error
//require("controllers/error.php");
return new ErrorController("badurl",$this->urlValues);
}
} else {
//bad controller error
//require("controllers/error.php");
return new ErrorController("badurl",$this->urlValues);
}
}
}
?>