我在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