Going Global in Drupal: Too good to be true?

There is a timeless law that every serious blogger needs to remember. As this law doesn't seem to have a name yet, I'm naming it Gillmor's law , after Dan Gillmor. Roughly stated, the law is:

"Your readers know more than you do."

I've discovered a solution to a common drupal programing problem: how to avoid excessively running something along the lines of "$node = node_load(arg(1));" in hooks or functions that don't have node data available to them.

The solution was so easy, and had so many different uses in different contexts that I'm nervous, and know that I must have done something idiotic. Thats where you, my dear reader, come in[1].

How to make the data from a node accessible from any php script in a drupal site

No matter where you are in drupal code, be it a module, a .inc file, or a theme, you can always access information about the current user using "global $user;". For those who aren't vetern drupal programmers, you can begin to see how to take advantage of this by inserting the following code in a page.tpl.php file.

global $user;

How can you make magic global $variables? Good question, reader.


Here's a magic hook nodeapi function to include in a module that will make any node object's data available to every module, theme, or include, so long as the node's $page variable is set to TRUE.

* Implementation of hook_nodeapi().
* Adds the global $node_view variable which is accessable everywhere by "global $node_view;"
function your_module_nodeapi(&$node, $op, $teaser, $page) {
switch ($op) {
case 'view':
if ($page == TRUE) {
// if you wanted to name the variable "lard", than write it as $GLOBALS['lard'];
$GLOBALS['node_view'] = $node;

Now, to my readers who know more than me: set me straight on what's wrong with globals. Why doesn't the drupal core make a global variable for $node available when $page == TRUE?[2]


1. No one seems to comment when asked, so for that reason, I'm writing this note in an attempt at reverse psychology. Please do not comment on that.

2.It seems like the core is where it should happen since lots of 3rd party contribs all with their own name for a global $variable seems like the biggest draw back to this approach.