6

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
);
Laxman13
  • 5,226
  • 3
  • 23
  • 27
Allain Lalonde
  • 91,574
  • 70
  • 187
  • 238
  • I'd be interested if you've tried it and it didn't work. The answer probably boils down to if PHP supports calling a function dynamically like this. $foo = 'MyClass::test'; $foo(); ... My initial thoughts would be no, but I haven't actually tried it. – Coder1 Apr 22 '11 at 16:21

2 Answers2

2

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']);
apaderno
  • 28,547
  • 16
  • 75
  • 90
1

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

Berdir
  • 6,881
  • 2
  • 26
  • 38