我在PHP中创建了一个基本的MVC结构化CMS,作为学习MVC如何工作的手段(因此我没有使用真正的预构建引擎)。我有一个基本版本,其结构与本教程here非常相似。不过,我想要自动加载视图,而不需要模板类。如果强烈建议,我会坚持使用模板概念(如果有人可以解释为什么它是如此必要,我将不胜感激)。无论如何,下面是我的路由器类,我修改了自动加载视图文件沿控制器。PHP 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转换为加载函数?
像你这样选择路由类中的视图模板是一个坏主意。不仅你假设每个动作都会呈现一个视图,而且视图只能有一个模板。一个单独的视图对象与从动作级别分配的模板和变量是更好的解决方案。 – lafor 2012-07-24 08:55:41