我目前正在重构我们的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);
}
}
}
- 其仍在开发中,尚未完全完成。
抛出一个异常并通过发送邮件来处理,听起来已经很漂亮了。也许发布一些代码片段? – Oli 2010-12-23 12:36:03