我的问题是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();
答案 0 :(得分:1)
parent::get()
get
方法中调用user
。否则你应该用user
另一个名字给出方法。
关于你的OO设计:我不明白你的代码的目的,但是你必须要问这个问题的事实暗示了糟糕的设计,是的。另外:可能错误使用继承,责任混合,命名不明确......
如果未设置$ _GET ['session'](该方法自行调用),这将导致无限递归:
function get(){
echo 'REQ_user method';
if(isset($_GET['session'])){
$this->session();
}else{
$this->get();
}