Surprised!Reflection & Delegation in PHP!!!!!!!!!!!
For the past few months i have been working in Django.Oh!!!!! Introspection & Introspection simply giving me some kind of madness for python.I am feeling the super power of it and couldn’t tie myself to write something about it.According to wikipedia Introspection means “It is a conscious and purposive process relying on thinking, reasoning, and examining one’s own thoughts, feelings, and, in more spiritual cases, one’s soul.” and this what exactly Introspection is.If you give access to read thoughts of one class then you are done!!!!!!Now what you have to do is just put a mirror in front of the class . PHP took few more time to discover this mirror
. It is in this rail from its 5 and 5+ version.
In PHP this can be achieved simply by using the delegation design pattern.You can explore the following code snippet, then close your eyes and think how could you use this power to enrich and boost the execution time.
class ClassOne {
function callClassOne() {
print “In Class One\n”;
}
}
class ClassTwo {
function callClassTwo() {
print “In Class Two\n”;
}
}
class ClassOneDelegator {
private $targets;
function __construct() {
$this->target[] = new ClassOne();
}
function addObject($obj) {
$this->target[] = $obj; //Register your object for Introspect
}
function __call($name, $args) {//the magic method of PHP again rocks in this case
foreach ($this->target as $obj) {
$r = new ReflectionClass($obj);
if($r->hasMethod($name)){
if ($method = $r->getMethod($name)) {
if ($method->isPublic() && !$method->isAbstract()) {
return $method->invoke($obj, $args);
}
}
}
}
}
}
$obj = new ClassOneDelegator();
$obj->addObject(new ClassTwo());
$obj->callClassOne();
$obj->callClassTwo();
Enjoy your time and never forget “Work should be fun”
.
