我的問題是,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();
您可以通過定義必須由子類實現的抽象方法來做到這一點。 – vikingmaster 2013-02-16 14:50:22