处理菜单未找到异常的最佳方法是什么?

时间:2010-12-23 12:24:14

标签: php exception-handling

我目前正在重构PHP CMS中的菜单类,我正在尝试找出最好的方法来处理有人试图创建菜单的问题(通过传入菜单的标题(我们有主菜单) ,页脚,实用程序等菜单),但菜单不在数据库中。

如果他们尝试使用可以找到的菜单创建菜单对象,那么没有问题,我可以按要求返回对象。如果他们试图创建一个找不到的,我正在抛出异常(导致发送电子邮件),然后创建一个空白菜单对象并返回它。输出菜单的调用然后可以正常工作,但不输出任何内容。

(我已经通过设置它完成了上述操作,因此调用菜单类的静态方法来创建一个菜单对象,然后可以在必要时处理抛出异常并返回所请求的菜单对象或空白一个)。

希望这一切都有意义!这是最好的方法吗?还是有更优雅的解决方案?

克里斯

编辑:

这是用于创建菜单的静态函数:

static function makeMenu($id,$breakDepth=1){
    // try to create Menu
    try {
        $menu = new Menu($id, $breakDepth);
    }
    catch (no_menu_found_exception $e) {
        // if we failed to find it, an email should have been sent, and create a blank menu so rest of site works without error
        $menu = new Menu("");
    }

    return $menu;
}

这是构造函数:

function __construct($id,$breakDepth=1){
    $this->treeObject = Doctrine_Core::getTable('CmsMenuItemNew')->getTree();
    if ($id == "") {
        // if ID supplied is empty, return an empty menu object 
        $this->rootNode = null;
        $this->name = $id;
        return;
    } 
    if (is_numeric($id)) {
        // check it exists?
        $this->rootNode = $id;
        $node = Doctrine_Core::getTable('CmsMenuItemNew')->findByDQL("menuid = '".$id."'")->getFirst();
        $this->name = $node->menutitle;
        if ($this->name == "") $this->rootNode = null;
        return;
    } else {
        $this->name = $id;
        // find the menu ID for the supplied name  
        $table = Doctrine_Core::getTable('CmsMenuItemNew');
        $table->setOption("orderBy", "level");
        $this->rootNode = $table->findByDQL("menutitle = '$id'")->getFirst()->menuid;

        // rootNode with supplied name not found, so look for a branch in the main menu
        $this->breakDepth = $breakDepth;    
        if ($this->rootNode === null) {
            throw new no_menu_found_exception("Menu not found: ".$id);
        }
    }           

}

如上所述 - 它仍处于开发阶段,尚未完全完成。

1 个答案:

答案 0 :(得分:0)

构建空白对象是件好事。正确的设计模式称为SpecialObjects。要完成,您的代码应该返回一个与MenuObject具有相同接口的MenuNotFound对象。 那么这个MenuNotFound对象对接口入口点的反应取决于你。 这样可以避免检查返回的对象类型并允许链接。

对于Exception,我个人更喜欢Exception,这只是真正的问题。但在您的情况下,如果您想要收到邮件,则异常并不是一个坏主意,也许这个异常或邮件处理可以在MenuNotFound init中完成。