Recipe 8.14 Writing a mod_perl Handler

Problem

You want to write your own mod_perl handler.

Solution

Here's a simple handler:

package Apache::Cookbook::Example;          sub handler {     my $r = shift;     $r->send_http_header( 'text/plain' );     $r->print( "Hello, World." ); } 1;

Place this code in a file called Example.pm, in a directory Apache/Cookbook/, somewhere that Perl knows to look for it.

Discussion

The example handler given is fairly trivial and does not do anything useful. More useful examples may be obtained from the mod_perl web site (http://perl.apache.org/) and from Geoffrey Young's (et al.) excellent book mod_perl Developer's Cookbook. Also, although it is somewhat dated, the "Eagle book" (Writing Apache modules with Perl and C) by Lincoln Stein and Doug MacEachern (O'Reilly) is an excellent introduction to mod_perl and the Apache API.

The real question here, however, is how and where you should install the file that you've created. There are two answers to this question, and which one you choose will be largely personal preference.

When Perl looks for a module, it looks through the list called @INC for directories where that module might be. You can either put your module in one of those directories, or you can add a directory to the list.

To find out where Perl is looking, you can examine the values stored in @INC with the following:

perl -le 'print join "\n", @INC;'

This will give you a listing that will look something like:

/usr/local/lib/perl5/5.8.0/i686-linux /usr/local/lib/perl5/5.8.0 /usr/local/lib/perl5/site_perl/5.8.0/i686-linux /usr/local/lib/perl5/site_perl/5.8.0 /usr/local/lib/perl5/site_perl .

This will of course vary from one system to another, from one version of Perl to another, but will bear some resemblance to that listing.

To install a module called Apache::Cookbook::Example, you might put the file Example.pm at the location /usr/local/lib/perl5/site_perl/5.8.0/Apache/Cookbook/Example.pm.

Alternately, you can tell Perl to look in some other directory by adding a value to the @INC list. The best way to do this is to add the following to your startup.pl file:

use lib '/home/rbowen/perl_libs/';

startup.pl should then be loaded by Apache at startup, using the directive:

PerlRequire /path/to/startup.pl

This tells Perl to also look in that directory for Perl modules. This time, if your module is called Apache::Cookbook::Example, you would now place it at the location /home/rbowen/perl_libs/Apache/Cookbook/Example.pm

See Also

  • mod_perl Developer's Cookbook by Geoffrey Young, et al, at http://modperlcookbook.org/.



Apache Cookbook
Apache Cookbook: Solutions and Examples for Apache Administrators
ISBN: 0596529945
EAN: 2147483647
Year: 2006
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net