在PHP MVC应用程序中将数据从Controller传递到View
发布时间:2020-12-13 13:19:58 所属栏目:PHP教程 来源:网络整理
导读:在SO的几乎所有教程或答案中,我看到了一种将数据从Controller发送到View的常用方法,类View通常看起来类似于下面的代码: class View{ protected $_file; protected $_data = array(); public function __construct($file) { $this-_file = $file; } public f
|
在SO的几乎所有教程或答案中,我看到了一种将数据从Controller发送到View的常用方法,类View通常看起来类似于下面的代码:
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;
从逻辑上讲,对视图数据进行分组并将其与内部视图类属性区分开来是有意义的.
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];
}
}
}
如果您尝试访问不存在的属性,将调用 $view = new View('home.php');
$view->set('title','Stackoverflow');
在模板中: <title><?php echo $this->title; ?></title> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
