Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Are you using menu_get_object()? Because you should be.

Parent Feed: 

So are you? You probably are, the function's been around for a while. But it's okay if you aren't. I wasn't for the longest time. But now I am, and so should you. 

So what does it do? Well, somewhat surprisingly, the documentation explains it quite well:

"menu_get_object() provides access to objects loaded by the current router item. For example, on the page node/%node, the router loads the %node object, and calling menu_get_object() will return that."

Before I knew about menu_get_object(), I was naively using the following code in my themes and modules to load the current page's node object:

if (arg(0) == 'node' && is_numeric(arg(1)) {
  $node = node_load(arg(1));
}

But now, I can just do this:

$node = menu_get_object();

Cleaner, right?

Also, it has the added bonus of being able to load any object loaded by the current router item. Nodes are just the default. Try it with users, taxonomy terms or even comments. Just remember you have to specify the type of the object and the position of the object ID in the path if you're loading something other than nodes.

$user = menu_get_object('user', 1);

A closing note: This function was actually introduced in Drupal 6 and it was recommended that you use it because the objects returned by menu_get_object() were statically cached by a function it used, menu_get_item(). However in Drupal 7 all entities, including nodes, are statically cached so the performance boost you used to see from menu_get_object isn't really there anymore.

I still think it's neat though and I'm going to keep using it anyway.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web