2013-02-16 53 views
0

我的問題是,REQ類將調用REQ_User的get()方法,而不是用戶的get()方法。調用類子方法而不是它的孫子方法

是否有必要讓REQ類調用REQ_User的get()方法。 或者這是一個糟糕的OOP設計?我可以做更好的面向對象設計嗎?

REQ是處理通用路由的主要路由器。

abstract class REQ{ 
    function get(){die('get() is not available');} 
    function get_id($id){die('get_id() is not available');} 
    function __construct(){ 
     http_response_code(500);//We dont know if its gonna be an unknown error in the future. 
     if($_SERVER['REQUEST_METHOD']==='GET' && isset($_GET['id'])) 
      $this->get_id((int)$_GET['id']); 
     elseif($_SERVER['REQUEST_METHOD']==='GET') 
      //Heres is the actual problem of my question. 
      //This will call the youngest child class which is user's get() method. 
      //I need it to call the REQ_User's get() method instead. 
      $this->get(); 

     //Much more routes is supposed to be here like post,delete,put etc. But this is just a example. 
    } 
} 

REQ_User增加了更多的能力比REQ可以做。僅專門用於用戶管理器類的功能。

abstract class REQ_User extends REQ{ 
    function session(){die('session() is not available');} 
    function get(){//I need this method to be called instead of user's get() method. 
     if(isset($_GET['session'])){ 
      $this->session(); 
     }else{//Call either its parent or its child but never its self. 
      if(get_class($this) === __CLASS__) parent::get(); 
      else $this->get(); 
     } 
    } 
} 

REQ_Comment增加了更多的能力比REQ可以做。只能用於評論管理員類的功能。 *注意get()不會調用它的self,但只有它的父或它的子節點取決於子節點是否得到了方法get()或不是。

實際的邏輯來自這些類。頂級的課程。 這些類是超專業的。

class user extends REQ_User{ 
    //If no url parameter is set then this will get a collection of users. 
    function get(){ 
     http_response_code(200); 
     die('user1,user2...'); 
    } 
    function session(){ 
     http_response_code(200); 
     session_start(); 
     die(json_encode($_SESSION['user'])); 
    } 
}; 
class comment extends REQ_Comment{ 
    function byuser($id){//Specialized route only for comments based classes. 
     http_response_code(200); 
     die('comment1,comment2... by user '.$id); 
    } 
    function get_id($id){//This comes directly from REQ class. 
     http_response_code(200); 
     die('user '.$id); 
    } 
}; 

//new comment(); 
//new user(); 
+0

您可以通過定義必須由子類實現的抽象方法來做到這一點。 – vikingmaster 2013-02-16 14:50:22

回答

1

呼叫parent::get()get方法user如果雙方應該叫內。否則,你應該只給user另一個名字的方法。

關於你的面向對象設計:我不明白你的代碼的目的,但事實是,你必須提出這個問題暗示糟糕的設計,是的。另外:繼承,責任的混合物,命名不清的可能是錯誤的用法......

,這將導致無窮遞歸,如果$ _GET [「會議」]沒有設置(在方法調用本身):

function get(){ 
    echo 'REQ_user method'; 
    if(isset($_GET['session'])){ 
     $this->session(); 
    }else{ 
     $this->get(); 
    } 
+0

它很難解釋設計,但我會更新代碼並糾正無限遞歸問題。也許它會清除設計的想法。它應該消除dublicate代碼,併爲不同類型的管理器類提供某種標準接口。 – Jossi 2013-02-17 16:15:59

+0

兩者都需要按正確順序調用是。原則是父母只能打電話給他的孩子,而孩子只能打電話給他的孩子等,而不是跳過來打電話給他的孫子。添加parent :: get()不會解決問題,因爲子進程將調用其父進程,並且父進程將調用其子進程,從而導致無限遞歸。 – Jossi 2013-02-17 16:59:53