【问题标题】:Where do I throw the exception?我在哪里抛出异常?
【发布时间】:2013-02-08 08:24:55
【问题描述】:

我有以下 php 函数,它根据路径数组呈现模板数组。换句话说,如果您提供一组数组,例如:

$array_template = array(
    'carousel' => 'carousel', //type=>name (with out extension).
    'mini' => 'mini_feed'
)

$array_paths = array(
    'path_one' => 'path/to/one/',
    'path_two' => 'path/to/two/'
)

到这个函数:

protected function _render_templates_array($templates, array $template_name){
    foreach($template_name as $type=>$name){
        foreach($templates as $template=>$path){
            if(file_exists($path . $name . '.phtml')){
                require_once($path . $name . '.phtml');
            }
        }
    }

    return;
}

它应该找到并渲染每个文件,检查该文件的每个路径。

我遇到的问题是,我想出了如何在找到所有文件后停止搜索,但是,我是否将 else 附加到 if 并抛出我的错误?还是我应该在其他地方抛出错误?

基本上我需要:

  1. 渲染所有模板,确保查看这些模板的所有路径。
  2. 如果在任何路径中都找不到模板,则会引发错误。
  3. 加载所有文件后停止处理。

想法?

【问题讨论】:

  • 这完全取决于您的应用程序需要做什么。如果您可以应付找不到模板,请继续使用其他模板。如果找到模板很重要,而您找不到模板,则停止并抛出异常。完全是您的选择。

标签: php arrays exception loops foreach


【解决方案1】:

在两个foreach 行之间,添加$found = false;。在if 内,添加$found = true; 在两个“end foreach”之间},根据需要添加if(!$found) throw.....;

protected function _render_templates_array($templates, array $template_name){
    foreach($template_name as $type=>$name){
        $found = false;
        foreach($templates as $template=>$path){
            if(file_exists($path . $name . '.phtml')){
                require_once($path . $name . '.phtml');
                $found = true;
            }
        }
        if( !$found) throw new .......;
    }

    return;
}

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 1970-01-01
    • 2019-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    相关资源
    最近更新 更多