0

这是另一种实用程序,每个博主\导师都假设我们都知道它是什么,因此他们从不费心解释它的实际作用。他们只是继续在他们的例子中使用它,相信我们都知道发生了什么。

从人们使用或引用的方式来看render(),它会建议它显示内容(例如:查看内容),但如果是这样,那么我们为什么要使用echo它来实际显示它的内容呢?

其他用途表明它格式化内容,如在内部我们sprintf()用来将变量注入字符串的表单装饰器中使用的那样。

那么在,等render()情况下会做什么呢?有人可以解释它在基本层面上的工作原理(引擎盖下)。谢谢。Zend_ViewZend_Layout

4

1 回答 1

3

它加载一个视图脚本并将其作为字符串输出。

稍微简化一下,Zend_View获取一个视图脚本文件(如 index.phtml)并在内部包含它以生成 HTML 输出。通过使用该render()方法,可以获取一个额外的视图脚本(例如 nav.phtml)并将其输出到您的父视图脚本中。这个想法是只渲染一次在许多页面上重复的元素,而不是一遍又一遍地重复相同的 HTML。

可以在Zend_View_Abstract类中找到 render 方法的代码,如下所示:

/**
 * Processes a view script and returns the output.
 *
 * @param string $name The script name to process.
 * @return string The script output.
 */
public function render($name)
{
    // find the script file name using the parent private method
    $this->_file = $this->_script($name);
    unset($name); // remove $name from local scope

    ob_start();
    $this->_run($this->_file);

    return $this->_filter(ob_get_clean()); // filter output
}

_run()方法的实现可以在类中找到,Zend_View如下所示:

/**
 * Includes the view script in a scope with only public $this variables.
 *
 * @param string The view script to execute.
 */
protected function _run()
{
    if ($this->_useViewStream && $this->useStreamWrapper()) {
        include 'zend.view://' . func_get_arg(0);
    } else {
        include func_get_arg(0);
    }
}

As you can see, render() takes a view script name, resolves its file name, initiates output buffering, includes the view script file (this is what the _run() method does internally), then passes the output through optional filters and finally returns the generated string.

The neat thing about it is that it retains the properties (variables) of the view object it is called from (because it's the same Zend_View object, just with a different view script loaded). In this respect, it differs from the partial() method, which has its own variable scope and you can pass variables into it (making it useful for rendering smaller elements, such as single rows of data when you foreach over a dataset).

于 2013-03-06T21:34:10.327 回答