查看Cake PHP中是否存在视图文件(.ctp)的最佳方法是什么?

时间:2015-10-26 03:29:37

标签: php cakephp view

我正在使用CakePHP 3,并希望更改随安装一起提供的方便的PagesController的行为。

他们在尝试查找和呈现视图文件(.ctp)时使用的当前解决方案是使用try {}块,该块运行良好。 实际代码:

try {
        $this->render(implode('/', $path));
} catch (MissingTemplateException $e) {

但在我的情况下,最常见的情况是.ctp文件不存在。 (如果它不存在,它将继续使用默认视图并尝试从数据库中获取内容,但这不是我的问题。)

在我的修改版本中,最常见的情况是抛出MissingTemplaceException,这看起来有点矫枉过正。 为什么我不能简单地检查文件是否存在?

我在想这里吗?如果我是,我如何检查文件的存在?

经过一番摆弄后,我发现APP不变。这有效:

$path = func_get_args();
$file = APP.'Template'.DS.'Pages'.DS.implode('/', $path).'.ctp';
if (file_exists($file))
{
  // Render the file.
}
else
{
  // Render some default file.
}

1 个答案:

答案 0 :(得分:1)

  

为什么我不能简单地检查文件是否存在?

我不知道为什么不能。只需使用file_exists()

if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
    echo "The file $filename does not exist";
}
相关问题