Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Apache Request Object

You need to retrieve the Apache request object.

Technique

Use the request() method from the Apache class to construct the request object directly

 my $r = Apache->request;

or, more idiomatically, simply pull the request object off of the argument list from a handler or Apache::Registry script

 my $r = shift;

Comments

The Apache request object is at the center of the mod_perl API. It provides access to the Apache request record as well as other core mod_perl methods—almost all the things that you will want to either peek at or manipulate. Nearly all of your mod_perl–specific code will begin by capturing the request object using one of the two methods shown here.

The Apache request object, like all objects in Perl, is merely a data structure bless()ed into the Apache class. The constructor for the Apache class is the request() method, which returns a new request object. Unlike traditional objects, however, the Apache request object has singleton-like properties—every request object created for a given request points to the same Apache request record and manipulates the same set of per-request data. Traditionally, most programmers end up placing the request object into $r, which is how you will see it appear throughout this book.

Because creating the Apache request object is such a frequent task, the request object is the first argument passed to mod_perl handlers. Well, unless your handler is a method handler, in which case the first argument is the invoking class, but we'll save that until Chapter 10.

As we already mentioned, because Apache::Registry is an example of a mod_perl handler, the request object is also the first argument passed to Registry scripts.

Although the idiomatic code of the second example is far more prevalent in both this book and on CPAN, the request() method is sometimes a preferable way to cleanly get at the request object. For instance, if you are writing a Perl module that needs to be intelligent about whether it is running under mod_perl or mod_cgi, you can effectively retrieve the request object using the request() syntax.

if ($ENV{MOD_PERL}) {
 my $r = Apache->request;
 $r->send_http_header('text/html');
}
else {
 print "Content-type: text/html\n\n";
}

As mentioned in the Introduction, the request object offers methods for accessing the fields of the Apache request record. The most important methods are described in the remaining recipes in this chapter, which will give you a glimpse into some of the more fundamental, interesting, and practical uses for mod_perl and $r. A few of the less-frequented methods are saved until later chapters where we show them in specific applications.

  • + Share This
  • 🔖 Save To Your Account