O'Reilly logo

Writing Apache Modules with Perl and C by Lincoln Stein, Doug MacEachern

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.11. Subclassing the Apache Class

It's appropriate that the last topic we discuss in this chapter is the technique for extending the Apache class itself with Perl's subclassing mechanism. Because the Perl API is object-oriented, you are free to subclass the Apache class should you wish to override its behavior in any way.

To be successful, the new subclass must add Apache (or another Apache subclass) to its @ISA array. In addition, the subclass's new() method must return a blessed hash reference which contains either an r or _r key. This key must point to a bona fide Apache object.

Example 7.14 subclasses Apache, overriding the print() and rflush( ) methods. The Apache::MyRequest::print method does not send data directly to the client. Instead, it pushes all data into an array reference inside the Apache::MyRequest object. When the rflush() method is called, the SUPER class methods, print and rflush, are called to actually send the data to the client.

Example 7.14. Apache::MyRequest Is a Subclass of Apache
package Apache::MyRequest;
use strict;

use Apache ();
use vars qw(@ISA);
@ISA = qw(Apache);

sub new {
    my($class, $r) = @_;
    $r ||= Apache->request;
    return bless {
       '_r' => $r,
       'data' => [],
    }, $class;
}

sub print {
    my $self = shift;
    push @{$self->{data}}, @_;
}

sub rflush {
    my $self = shift;
    $self->SUPER::print("MyDATA:\n", join "\n", @{$self->{data}});
    $self->SUPER::rflush;
    @{$self->{data}} = ();
}

1;
__END__

Here is an example of an Apache::Registry script that uses Apache::MyRequest ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required