2010-12-23 44 views
0

我目前正在重構我們的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); 
     } 
    }   

} 

- 其仍在開發中,尚未完全完成。

+0

拋出一個異常並通過發送郵件來處理,聽起來已經很漂亮了。也許發佈一些代碼片段? – Oli 2010-12-23 12:36:03

回答

0

建立一個空白對象是一件好事。正確的設計模式稱爲SpecialObjects。爲了完成你的代碼,應該返回一個與MenuObject具有相同接口的MenuNotFound對象。 然後,MenuNotFound對象對接口入口點的反應方式取決於您。 這樣可以避免檢查返回的對象的類型並允許鏈接。

對於例外我personnaly喜歡異常這只是真正的問題。但在你的情況下,如果你想獲得一個郵件,異常並不是一個壞主意,也許這個異常或郵件處理可以在MenuNotFound初始化中完成。

+0

SpecialObjects設計模式也被稱爲空對象模式? – 2010-12-23 19:37:11