View-like Path Arguments in hook_menu()

Comments

AjK writes:

Here's a slightly different way to do it (this is for Drupal 5):-

<?php
function example_menu($may_cache) {
 
$items = array();
  if (!
$may_cache) {
   
$items[] = array(
     
'path' => arg(0) .'/foo',
     
'type' => MENU_CALLBACK,
     
'callback' => '_example_router',
    );
  }
  return
$items;
}

function _example_router() {
 
$args = func_get_args();

  if (!count($args)) {
   
drupal_not_found();
  }
  else {
    switch (
array_shift($args)) {
      case
'bar':
        return
_example_bar_handler($args);
        break;
      case
'baz':
        return
_example_baz_handler($args);
        break;
      case
'ban':
        return
_example_ban_handler($args);
        break;
      default:
       
drupal_not_found();
    }
  }

  return;
}
?>

So, what's going on here? Well, in the hook_menu() we define a single path. That path, and any children, will call your router function. Additionally, any path children will be passed as parameters to your router function.

These are retrieved with a func_get_args() and we now have any children path elements as an array.

The rest should be obvious. Seems like more code but there are some advantages. First, if arg(0) is fixed for your module you can wrap the menu item in if ($may_cache) and have your path cached.

Second, if you have a very big module you could put functionality into various include files. Then, you include them after the case: terms. That way you can a) make your module modular itself and b) your code is only included (parsed by PHP) when your exact URL path is hit. Additionally you can have finer grained access control at each case: point using drupal_access_denied().

Last, you get the opportunity to pass any further child path elements to your handler functions. Yes, I know, arg(x) can do that. But for those who don't know, arg() function is depreciated.

One last advantage, when it comes time to upgrade to Drupal 6 this way of laying out your menu hook will make your life simpler.