Popular just now

ad1

Build a Drupal style hook system using PHP reflection

The Movico module is a scaffold for building Drupal modules in OOP and MVC. One requirement of the project is a hooking system, similar to Drupals, that uses OOP. The following is how I plan to build such a system using the PHP 5 reflection API.

This code shows how using Reflection makes it easy to create a system that hooks into several Class methods to build a linked menu. This moves two systems that are heavy resource users and overly cached from Drupal and places them into the Movico domain.

To try this out you can download and install the Movico module, place this code in ...movico/_controllers/hooks.class.inc. Then surf to ?q=app/hooks/get_hooks. If you get a access denied page then add this to the mvc.module

Update: Moving to hiveminds.Wordpress.com to get syntaxhighlighting and Linkedin connectivity


function mvc_access($uri){

$authorize = array(
'hello' => array('access foo'),
'hello_log' => array('access baz'),
'hello_log_view' => array('access foo','access baz'),
'get_hooks' => array('access foo','access baz'),
);



...movico/_controllers/hooks.class.inc
======================================



/**
* Normally the Classes would be in individual files and loaded via an iterator
*
*
* @author Carl McDade
* @since 2010-02-18
*/
class ConClass1 {

function hook_output()
{
$var[1] = 'link text(1)';
$var[11] = 'link text(11)';

return $var;
}
}

class ConClass2 {

function hook_output()
{
$var[2] = 'link text(2)';

return $var;
}
}

class ConClass3 {

function hook_output()
{
$var[3] = 'link text(3)';
$var[4] = 'link text(4)';

return $var;
}
}

class hooks{

public $hook = 'hook_output';
public $arr = array();

function _modules()
{
$vars = array('ConClass1','ConClass2','ConClass3');

return $vars;
}

function get_hooks()
{
foreach ($this->_modules() as $module)
{
$Class = new ReflectionClass($module);
$Method = new ReflectionMethod($Class->getName(), $this->hook);

if ($Method->isStatic())
{
$output = $Method->invoke(NULL);
}
else{

$instance = $Class->newInstance();
$this->arr = array_merge($this->arr, $Method->invoke($instance));
}
}

return mvc_view('default', $variables, implode('',$this->arr));
}
}

?>

3 comments:

  1. Valuable education on would get on PHP, thanks and have bookmarked, please keep sharing many more!@bose
    Template cv

    ReplyDelete
  2. Very useful and needed this one..Thanks a lot for sharing this with me!

    Designer Resume Templates

    ReplyDelete
  3. There has been some more activity on StackOverflow about the PHP Reflection API and performance: http://stackoverflow.com/questions/294582/php-5-reflection-api-performance

    ReplyDelete