Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a static method as a menu callback in drupal?

When defining a hook_menu item can I use a public static method on a class rather than using the global underscore naming convention drupal tends to go for?

For example, is the following acceptable?

$items['test'] = array(
  'page callback' => 'MyClass::test',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK
);
like image 871
Allain Lalonde Avatar asked Apr 22 '11 14:04

Allain Lalonde


2 Answers

menu_execute_active_handler(), which is the Drupal function that calls the menu callback, contains the following code:

if ($router_item = menu_get_item($path)) {
  if ($router_item['access']) {
    if ($router_item['file']) {
      require_once($router_item['file']);
    }
    return call_user_func_array($router_item['page_callback'], $router_item['page_arguments']);
  }
  else {
    return MENU_ACCESS_DENIED;
  }
}

In PHP 5.2.3, or higher, is possible to call call_user_func() as call_user_func('MyClass::myCallbackMethod').

The only problem I can see is with third-party modules that don't expect a menu callback is a class static method, and use function_exists($menu_callback).
Then, as Coder1 reported, if Drupal core modules, or other modules, try to call the menu_callback using code similar to the following, then they could cause a PHP error.

$menu_callback = $router_item['page_callback'];
$menu_callback($router_item['page_arguments']);
like image 78
apaderno Avatar answered Nov 04 '22 15:11

apaderno


Yes, it should work, as this does:

class Test {
  static function method() { echo 'Yes'; }
}

$name = 'Test::method';
call_user_func_array($name, array());

However, why would you want to do that?

As you said, It is common to use normal functions (which you can have lazy loaded when necessary by the menu system automatically) for page callbacks.

If you work with Drupal, you should follow the official coding standard. Even if this is for custom modules only. If someone needs to pick up your work at some point, it will be easier for them if the code follows the same standard that is used everywhere else.

See also http://groups.drupal.org/node/20728#comment-71907

like image 37
Berdir Avatar answered Nov 04 '22 14:11

Berdir