在几乎所有关于SO的教程或答案中,我看到了一种将数据从控制器发送到视图的常用方法,类视图通常看起来与下面的代码相似:
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;发布于 2013-06-25 00:01:42
从逻辑上讲,对视图数据进行分组并将其与内部视图类属性区分开来是有意义的。
PHP将允许您动态分配属性,因此您只需实例化View类并将视图数据作为属性分配即可。但就我个人而言,我不推荐这样做。如果您想遍历视图数据,或者只是为了调试而简单地转储它,该怎么办?
将视图数据存储在数组中或包含对象并不意味着必须使用$this->get('x')来访问它。一种选择是使用php5的Property Overloading,这将允许您将数据存储为数组,同时使用来自模板的数据的$this->x接口。
示例:
class View
{
    protected $_data = array();
    ...
    ...
    public function __get($name)
    {
        if (array_key_exists($name, $this->_data)) {
            return $this->_data[$name];
        }
    }
}如果您试图访问一个不存在的属性,则将调用__get()方法。因此,您现在可以这样做:
$view = new View('home.php');
$view->set('title', 'Stackoverflow');在模板中:
<title><?php echo $this->title; ?></title>发布于 2013-06-25 00:00:02
我猜原因可能仅仅是“减少了打字”,但这也有一些好的副作用:
当编写模板的人不熟悉php时,
$this->意味着什么?”当视图的某些属性应该是该类的私有属性,并且库编写者不想让它们与视图自己的属性和templates.https://stackoverflow.com/questions/17279230
复制相似问题