Location: PHPKode > scripts > QDispatcher > dispatcher.class.php
<?php

/**
 * class dispatcher using Reflection to execute classes
 * @author Thomas Schäfer <hide@address.com>
 * @example Dispatcher::execute("class", "method", array($parameter))
 */
/**
 * class dispatcher using Reflection to execute classes
 * @author Thomas Schäfer <hide@address.com>
 * @example 
 * Dispatcher::execute("sampleclass", "samplemethod", array(1,2,3), array("data", true));
 * is equivalent to
 * $obj = new sampleclass("data", true);
 * $obj->samplemethod(1,2,3);
 */
class Dispatcher
{

  /**
   * @param string $class
   * @param atring $method
   * @param array $parameters
   * @param array $constructor
   * @return mixed
   */
  public static function execute($class, $method, array $parameters = array(), array $constructor = null)
  {

    $returnValue = null;
    $instance = null;

    try
    {
      $className = $class;
      $methodName = $method;

      $reflectObj = new ReflectionClass($className);

      if($reflectObj->hasMethod("__construct"))
      {
        $reflectMthd = new ReflectionMethod($className, "__construct");
        if($reflectMthd->getNumberOfParameters()>0)
        {
          $instance = $reflectObj->newInstanceArgs($constructor);
        }
      }

      if($reflectObj->hasMethod($methodName))
      {
        $actingMethod = new ReflectionMethod($className, $methodName);
        if($actingMethod->isPublic())
        {
          $instance = (!empty($instance)?$instance:$reflectObj->newInstance(array()));
          if($actingMethod->getNumberOfParameters()>0)
          {
            $returnValue = $actingMethod->invokeArgs($instance, $parameters);
          }
          else
          {
            $returnValue = $actingMethod->invokeArgs($instance, array());
          }
          return $returnValue;
        }
        else
        {
          throw new Exception("dispatched class method has to be public.");
        }
      }
      else
      {
        throw new Exception("class $class does not exist.");
      }
    }
    catch (Exception $e)
    {
      return $e->getMessage();
    }
  }

}
Return current item: QDispatcher