【发布时间】: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?