我可以在 drupal 中使用静态方法作为菜单回调吗?
在定义 hook_menu
项时,我可以在类上使用公共静态方法,而不是使用 drupal 倾向于使用的全局下划线命名约定吗?
例如,以下内容可以接受吗?
$items['test'] = array(
'page callback' => 'MyClass::test',
'access arguments' => array('access content'),
'type' => MENU_CALLBACK
);
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
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
menu_execute_active_handler(),这是Drupal调用菜单回调的函数包含以下代码:
在 PHP 5.2.3 或更高版本中,可以将
call_user_func()
调用为call_user_func('MyClass::myCallbackMethod').
我能看到的唯一问题是不期望菜单回调的第三方模块是类静态方法,并使用
function_exists($menu_callback)
。然后,正如 Coder1 报告的那样,如果 Drupal 核心模块或其他模块尝试使用类似于以下的代码调用 menu_callback,那么它们可能会导致 PHP 错误。
menu_execute_active_handler(), which is the Drupal function that calls the menu callback, contains the following code:
In PHP 5.2.3, or higher, is possible to call
call_user_func()
ascall_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.
是的,它应该有效,就像这样:
但是,你为什么要这样做呢?
正如您所说,通常使用普通函数(必要时可以由菜单系统自动延迟加载)进行页面回调。
如果您使用 Drupal,则应该遵循官方编码标准。即使这仅适用于自定义模块。如果有人需要在某个时候接手您的工作,如果代码遵循与其他地方使用的相同标准,对他们来说会更容易。
另请参阅http://groups.drupal.org/node/20728#comment-71907
Yes, it should work, as this does:
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