我的问题是 REQ 类将调用 REQ_User 的 get() 方法而不是用户的 get() 方法。
是否可以让 REQ 类调用 REQ_User 的 get() 方法。或者这是一个糟糕的 OOP 设计?有没有更好的 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 所能做的更多的能力。仅适用于评论管理器类的能力。
abstract class REQ_Comment extends REQ{
function byuser($id){die('byuser() is not available');}
function get(){
if(isset($_GET['byuser'])) $this->byuser( (int)$_GET['id'] );
else{//Call either its parent or its child but never its self.
if(get_class($this) === __CLASS__) parent::get();
else $this->get();
}
}
}
*请注意,get() 不会调用它自己,但只有它的父级或它的子级取决于子级是否获得方法 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();