Friday, August 10, 2012

Like to explore something new in PHP?

Few months i worked in a Django project.Oh!!!!! Introspection and Introspection, simply gave me some kind of madness for python.I really observed the super power of it through out the project and couldn't tie myself to write something about it.Introspection 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);

               }

            }

         }

      }

   }

}
Testing the snipplet:
$obj = new ClassOneDelegator();

$obj->addObject(new ClassTwo());

$obj->callClassOne();

$obj->callClassTwo();
Enjoy your time and never forget "Work should be fun" :D.

No comments:

Post a Comment

SyntaxHighlighter