我正在 PHP 中创建一个基本的 MVC 结构化 CMS,作为了解 MVC 工作原理的一种方式(因此我没有使用真正的预构建引擎)。我有一个基本版本,其结构与本教程非常相似。但是,我希望自动加载视图,绕过对模板类的需求。如果强烈建议这样做,我会坚持使用模板概念(如果有人能解释为什么它如此必要,我将不胜感激。)无论如何,下面是我的路由器类,我已经修改它以自动加载控制器中的视图文件。
public function loader() {
/*** check the route ***/
$this->getPath();
/*** if the file is not there diaf ***/
if (is_readable($this->controller_path) == false) {
$this->controller_path = $this->path.'/controller/error404.php';
$this->action_path = $this->path.'/view/error404.php';
}
/*** include the path files ***/
include $this->controller_path;
include $this->action_path;
/*** a new controller class instance ***/
$class = $this->controller . 'Controller';
$controller = new $class($this->registry);
/*** check if the action is callable ***/
if (is_callable(array($controller, $this->action)) == false) {
$action = 'index';
} else {
$action = $this->action;
}
$controller->$action();
}
/**
*
* @get the controller
*
* @access private
*
* @return void
*
*/
private function getPath() {
/*** get the route from the url ***/
$route = (empty($_GET['rt'])) ? '' : $_GET['rt'];
if (empty($route)) {
$route = 'index';
} else {
/*** get the parts of the route ***/
// mywebsite.com/controller/action
// mywebsite.com/blog/hello
$parts = explode('/', $route);
$this->controller = $parts[0];
if(isset( $parts[1])) {
$this->action = $parts[1];
}
}
if( ! $this->controller ) { $this->controller = 'index'; }
if( ! $this->action ) { $this->action = 'index'; }
/*** set the file path ***/
$this->controller_path = $this->path .'/controller/'. $this->controller . '.php';
$this->action_path = $this->path .'/view/'. $this->controller . '/'. $this->action . '.php';
}
这会阻止我的视图文件加载控制器给出的变量(教程网站对此有更好的演示)但是在设置$this->registry->template->blog_heading = 'This is the blog Index';
视图时不会加载它,因为 template.class 被绕过了。基本上我要问的是如何将 template.class 转移到加载函数中?