I have three classes. Class A
, Class B
, Class C
. What I am trying to do, send a request to Class B form Class A, and Class B must redirect that request to Class c.
May be a simple example from below will give a certain idea.
class classa {
public function __construct() {
$obj_classb = new classb;
$obj_classb -> someRequest(); // This request must go to Class B and query the Class C
}
}
class classb {
//This class must do something, which is going to redirect any sorts of request it receives to the next classc
}
class classc {
public function someRequest() {
//do whatever
}
}
Any Idea?
You can create a "redirector" class by overriding the __call
method like this:
class classb {
private $obj_classc;
public function __construct() {
$this->obj_classc = new classc;
}
public function __call($name, $arguments) {
return call_user_func_array(array($this->obj_classc, $name), $arguments);
}
}
Of course this will "forward" only method calls; if you are interested in forwarding property getters/setters etc you will have to override more magic methods.
Choosing the forwarding target can also be arranged (in this example it's just an automatically-created classc
object; but you can pass it as a parameter in the constructor or provide it in any other way you choose).
Update: Magic functions you need to override to forward property accesses:
public function __set($name, $value) {
$this->obj_classc->$name = $value;
}
public function __get($name) {
return $this->obj_classc->$name;
}
public function __isset($name) {
return isset($this->obj_classc->$name);
}
public function __unset($name) {
unset($this->obj_classc->$name);
}