render()在Zend Framework中做了什么

时间:2013-03-06 21:13:11

标签: zend-framework rendering zend-form

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

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

其他用途表明它格式化内容,就像在form-decorators中一样,我们在内部使用sprintf()将变量注入字符串。

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

1 个答案:

答案 0 :(得分: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);
    }
}

如您所见,render()获取视图脚本名称,解析其文件名,启动输出缓冲,包括视图脚本文件(这是_run()方法在内部执行的操作),然后通过通过可选过滤器输出,最后返回生成的字符串。

它的巧妙之处在于它保留了调用它的视图对象的属性(变量)(因为它是相同的Zend_View对象,只是加载了不同的视图脚本)。在这方面,它与partial()方法不同,后者具有自己的变量范围,您可以将变量传递给它(使其有助于渲染较小的元素,例如foreach时的单行数据在数据集上。)