问题描述
限时送ChatGPT账号..在几乎所有关于 SO 的教程或答案中,我看到了一种将数据从控制器发送到视图的常用方法,视图类通常看起来与下面的代码相似:
In almost all tutorials or answers on SO, I see a common way to send data from a Controller to the View, the class View often looks something similar than the code below:
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).为什么不直接将一些属性从控制器像
I don't understand why I need to put the data in an array and then call extract($this->_data). Why not just put directly some properties to the view from the controller like
$this->_view->title = 'hello world';
然后在我的布局或模板文件中我可以这样做:
then in my layout or template file I could just do:
echo $this->title;
推荐答案
将视图数据分组并将其与内部视图类属性区分开在逻辑上是有意义的.
It makes sense logically to group the view data and differentiate it from the internal view class properties.
PHP 将允许您动态分配属性,因此您只需实例化 View 类并将您的视图数据分配为属性.不过我个人不推荐这个.如果您想遍历视图数据,或者只是将其转储以进行调试,该怎么办?
PHP will allow you to dynamically assign properties so you could just instantiate the View class and assign your view data as properties. Personally I wouldn't recommend this though. What if you wanted to iterate over the view data, or just simply dump it for debugging?
将视图数据存储在数组或包含对象中并不意味着您必须使用 $this->get('x')
来访问它.一种选择是使用 PHP5 的 Property Overloading,它允许您将数据存储为一个数组,但具有带有模板数据的 $this->x
接口.
Storing the view data in an array or containing object dosn't mean that you have to use $this->get('x')
to access it. An option is to use PHP5's Property Overloading, which will allow you to store the data as an array, yet have the $this->x
interface with the data from the template.
示例:
class View
{
protected $_data = array();
...
...
public function __get($name)
{
if (array_key_exists($name, $this->_data)) {
return $this->_data[$name];
}
}
}
__get()
如果您尝试访问不存在的属性,则将调用方法.所以你现在可以这样做:
The __get()
method will be called if you try to access a property that doesn't exist. So you can now do:
$view = new View('home.php');
$view->set('title', 'Stackoverflow');
在模板中:
<title><?php echo $this->title; ?></title>
这篇关于将数据从控制器传递到 PHP MVC 应用程序中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论