【问题标题】:Best way to see if a view file (.ctp) exists in Cake PHP?查看 Cake PHP 中是否存在视图文件 (.ctp) 的最佳方法?
【发布时间】:2015-10-26 03:29:37
【问题描述】:

我正在使用 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.
}

【问题讨论】:

  • 为什么不直接在 catch 块中执行默认代码而不是抛出异常?
  • @arilia - 这就是我目前所做的,它有效。我只是认为检查文件是否存在会更快。

标签: php cakephp view


【解决方案1】:

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

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

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

【讨论】:

  • 对不起@burzum,我的问题不是很清楚。我想知道的是如何获得与 $this->render(implode('/', $path)); 相同的文件名必须产生然后渲染。一个例子:$path='that-page',最后会让 $this->render() 寻找文件 Template/Pages/that-page.ctp。
  • 查看我编辑的答案,我相信这里的主要问题是我在睡觉。 :P ;)
猜你喜欢
  • 1970-01-01
  • 2016-05-22
  • 2011-05-25
  • 2010-09-18
  • 2017-10-06
相关资源
最近更新 更多