Recipe 21.13 Sharing Information Between Handlers

21.13.1 Problem

You want to share information between handlers, but global variables are global to a process and not automatically cleaned up after every request.

21.13.2 Solution

Use Apache pnotes (Perl notes):

# in one handler
$r->pnotes("Name", $name);

# in another handler
$name = $r->pnotes("Name");

21.13.3 Discussion

Apache modules communicate with each other using notes (see Recipe 21.11). Apache notes act like a hash attached to a requestone handler stores a value for a key in the hash, so that another handler can read it later. The Perl notes features is also a hash attached to the request object, but it's only for the Perl handlers.

To set a pnote, pass a key and a value to the $r->pnotes method. To retrieve a pnote, pass only the key. You can store complex data structures:

$r->pnotes("Person", { Name => "Nat",
                       Age  => 30,
                       Kids => 2 });
# later
$person = $r->pnotes("Person");

and even objects:

$person = new Person;

$r->pnotes(Person => $person);

# later

$person = $r->pnotes("Person");
# $person is a reference to the same object

21.13.4 See Also

Recipe 8.11 in mod_perl Developer's Cookbook; Apache::Table; pnotes method in the Apache manpage