You are here

改变其它模块的菜单项

老葛的Drupal培训班 Think in Drupal

Drupal重构menu_router表和更新menu_link表时(比如,当一个新模块被启用时),通过实现hook_menu_alter(),模块就可以修改任意的菜单项。例如,“登出”菜单项通过调用user_logout()将当前用户登出,它将销毁用户的会话并将用户重定向到站点的首页。由于user_logout()函数位于modules/user/user.pages.inc,所以该Drupal路径的菜单项中定义了file键。所以,通常情况下,当一个用户点击了导航区块中的“登出”链接,Drupal会加载文件modules/user/user.pages.inc并运行user_logout()函数。
/**
* Implementation of hook_menu_alter().
*
* @param array $items
* Menu items keyed by path.
*/
function menufun_menu_alter(&$items) {
    // Replace the page callback to 'user_logout' with a call to
    // our own page callback.
    $items['logout']['page callback'] = 'menufun_user_logout';
    // Drupal no longer has to load the user.pages.inc file
    // since it will be calling our menufun_user_logout(), which
    // is in our module -- and that's already in scope.
    unset($items['logout']['file']);
}
 
/**
* Menu callback; logs the current user out, and redirects to drupal.org.
* This is a modified version of user_logout().
*/
function menufun_user_logout() {
    global $user;
 
    watchdog('menufun', 'Session closed for %name.', array('%name' => $user->name));
 
    // Destroy the current session:
    session_destroy();
    // Run the 'logout' operation of the user hook so modules can respond
    // to the logout if they want to.
    module_invoke_all('user', 'logout', NULL, $user);
 
    // Load the anonymous user so the global $user object will be correct
    // on any hook_exit() implementations.
    $user = drupal_anonymous_user();
 
    drupal_goto('http://drupal.org/');
}
    在我们的hook_menu_alter()实现运行以前,logout路径的菜单项应该是这样的:
array(
    'access callback' => 'user_is_logged_in',
    'file' => 'user.pages.inc',
    'module' => 'user',
    'page callback' => 'user_logout',
    'title' => 'Log out',
    'weight' => 10,
)
    当我们修改了它以后,就变成了这样:
array(
    'access callback' => 'user_is_logged_in',
    'module' => 'user',
    'page callback' => 'menufun_user_logout',
    'title' => 'Log out',
    'weight' => 10,
)

Drupal版本:

评论

感觉这个翻译似乎有点问题哈,是不是该改为:从其它的模块中改变菜单项。总之不是“改变其他模块的菜单项”这个意思。