为什么不检查ZF2中是否真的存在模板文件?

时间:2013-11-15 13:35:58

标签: php zend-framework2

在ZF 2.2.5 Zend\View\Renderer\PhpRenderer::render方法中,有一个if语句,用于检查模板堆栈中是否存在模板(第497行)

$this->__file = $this->resolver($this->__template);
if (!$this->__file) {
    throw new Exception\RuntimeException(sprintf(
        '%s: Unable to render template "%s"; resolver could not resolve to a file',
        __METHOD__,
        $this->__template
    ));
}
try {
    ob_start();
    include $this->__file;
    $this->__content = ob_get_clean();
} catch (\Exception $ex) {
    ob_end_clean();
    throw $ex;
}

但它不检查文件系统中是否确实存在文件。这意味着后续try { ... } catch(\Exception $ex) {...}块无用,因为include $this->__file;无法捕获。因此,当我测试我的控制器时,即使模板文件丢失也只有200响应,并且屏幕上只有异常调用堆栈。不应该将if (!$this->__file) { ... }重写为if (!is_file($this->__file)) { ... }吗?

1 个答案:

答案 0 :(得分:0)

嗯,由解析器执行这些检查。请参阅以下代码Zend\View\Resolver\TemplatePathStack

    foreach ($this->paths as $path) {
        $file = new SplFileInfo($path . $name);
        if ($file->isReadable()) {
            // Found! Return it.
            if (($filePath = $file->getRealPath()) === false && substr($path, 0, 7) === 'phar://') {
                // Do not try to expand phar paths (realpath + phars == fail)
                $filePath = $path . $name;
                if (!file_exists($filePath)) {
                    break;
                }
            }
            if ($this->useStreamWrapper()) {
                // If using a stream wrapper, prepend the spec to the path
                $filePath = 'zend.view://' . $filePath;
            }
            return $filePath;
        }
    }

另请注意,include接受超过is_file次检查。例如,include也接受stream wrappers