在幾乎所有教程或SO上的答案中,我都看到將數據從Controller發送到View的常用方法,View類通常看起來類似於以下代碼:將數據從控制器傳遞到PHP MVC應用程序中的視圖
class View
{
protected $_file;
protected $_data = array();
public function __construct($file)
{
$this->_file = $file;
}
public function set($key, $value)
{
$this->_data[$key] = $value;
}
public function get($key)
{
return $this->_data[$key];
}
public function output()
{
if (!file_exists($this->_file))
{
throw new Exception("Template " . $this->_file . " doesn't exist.");
}
extract($this->_data);
ob_start();
include($this->_file);
$output = ob_get_contents();
ob_end_clean();
echo $output;
}
}
我不明白爲什麼我需要把數據放入數組然後調用extract($ this - > _ data)。 爲什麼不乾脆直接就把一些屬性到視圖從控制器類似
$this->_view->title = 'hello world';
然後在我的佈局或模板文件我可能只是這樣做:
echo $this->title;
非常感謝你的摘錄,真棒!) – Matthew