如何检查Cakephp 3中是否存在元素?

时间:2015-10-14 11:06:21

标签: php cakephp

检查cakephp 3中是否存在元素,.ctp文件的最佳方法是什么?

像这样,

<?php
// if the elemet exist display it
$this->render('/Element/Trip/'.$current_step);
// else display another element instead
?>

谢谢:)

4 个答案:

答案 0 :(得分:4)

使用$this->elementExists

<?php
 if ($this->elementExists('Trip/'.$current_step)) {
   echo $this->element('Trip/'.$current_step);
 } else {
   echo $this->element('Trip/default.ctp');  
 } 

http://api.cakephp.org/3.2/class-Cake.View.View.html#_elementExists

如果您不想显示其他元素但不要抛出异常,则可以使用ignoreMissing选项

$this->element('Trip/'.$current_step,$data, ['ignoreMissing' => true])

答案 1 :(得分:3)

file_exists()并使用the Controller::$viewPath property

但这是恕我直言的不良做法,因为你应该知道你的元素,而不是依靠猜测。 $current_step意味着有一些步骤,猜测它们是有限的。因此,不要在视图中进行检查,而是检查步骤是否在控制器中的步骤范围从1到5,并且如果它没有抛出NotFoundException。该异常将返回404,因此您可以在通过JS处理客户端中的响应时检查对该状态代码的响应。

public function my_action($step) {
    if (!in_array($step, ['step1', 'step2', 'step3', 'done']) {
        throw new \NotFoundException();
    }
}

答案 2 :(得分:2)

<?php
// if the elemet exist display it
if(file_exists ('/Element/Trip/'.$current_step))
$this->render('/Element/Trip/'.$current_step);
else
// else display another element instead
?>

答案 3 :(得分:1)

你必须检查文件是否存在?如果文件存在然后做一些事情或做其他事情

<?php
// if element exists
$element='/Element/Trip/'.$current_step;
if(file_exists($element))
   $this->render($element);
else
{
   // Display another element.
}
?>