【问题标题】:Best way to handle menu not found exception?处理菜单未找到异常的最佳方法?
【发布时间】:2010-12-23 12:24:14
【问题描述】:

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

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

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

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

克里斯

编辑:

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

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);
        }
    }           

}

如前所述 - 它仍在开发中,因此尚未完全完成。

【问题讨论】:

  • 抛出异常并通过发送邮件来处理它听起来已经很优雅了。也许发布一些代码 sn-ps?

标签: php exception-handling


【解决方案1】:

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

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

【讨论】:

  • SpecialObjects 设计模式也称为 Null Object 模式?
  • 这听起来像是我想找的东西。所以在我的静态方法中,在 catch 段中,我会调用“new MenuNotFound()”吗?这意味着我不需要构造函数中凌乱的 'if ($id == "") {' 部分,我认为这是我认为必须有一个更简洁的解决方案的部分原因。我想这就是我一直在寻找的。我也同意抛出异常似乎有点弱 - 我想我可以检查它是否在静态方法中找到,所以我不必抛出异常来显示它没有找到。跨度>
  • 是的空对象,我总是提醒我特殊对象,但据我所知,空对象似乎是相同的模式。一个区别可能是 Null 对象在他的方法中不包含任何内容,他应该什么都不做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2016-12-07
  • 2023-01-28
  • 1970-01-01
相关资源
最近更新 更多