Apache2-Controller

 view release on metacpan or  search on metacpan

lib/Apache2/Controller.pm  view on Meta::CPAN

simply requires you to provide a hash that maps from uri paths to 
controller modules.  Or, dispatch plugins can be created to implement
the dispatcher's find_controller() method in some other way, like
with a TRIE for big sites or using other algorithms,
even dynamic ones based on context from the request.

L<Apache2::Controller> is the base module for each controller module. 
Depending on your dispatch mechanism, controller modules usually 
contain a list of the method names which 
are allowed as uri paths under the controller.

=head1 DISPATCH OF URI TO CONTROLLER

You do not put Apache2::Controller or your subclass into the
Apache2 server configuration.  Instead you make a subclass
of L<Apache2::Controller::Dispatch> and use that as a
PerlInitHandler.  It will map a URI to an appropriate
Apache2::Controller subclass object and method and will
use C<< $r->push_handlers() >> if successful to push Apache2::Controller
onto the modperl response handler stack, which then creates
the right handler object of your subclass and sends the
request to the right method, handling errors in a nice way.

See L<Apache2::Controller::Dispatch>
for more information and different types of URI dispatching.
Some simple types are bundled which depend on
the C<< allowed_methods() >> subroutine in your controller,
but that isn't a required feature - 
you can also implement your own dispatch subclass which
does things your way, moves allowed uris around depending
on context in the request, or whatever.

=head1 OTHER REQUEST PHASE HANDLERS

Configure other handlers in your config file to set things up
before your Apache2::Controller runs.

Most of these handlers use L<Apache2::Controller::NonResponseBase>
as a base for the object, which usually does not need to
instantiate the L<Apache2::Request> object, because they
usually run before the response phase, so you usually don't
want to parse and cache the body if you want to use input filters.
If your subclass methods of non-response Apache2::Controller
components need access to the L<Apache2::RequestRec> object C<< $r >>, 
it is always in C<< $self->{r} >>.

Some other request phase handlers register later-stage handlers,
for example to save the session or rollback uncommitted database 
transactions with C<PerlLogHandler>'s
after the connection output is complete.

The controller handler returns your set HTTP status code
or OK (0) to Apache.  In general you return the status code
that you want to set, or return OK.  Or you can set it with
C<< $r->status() >> and return OK.  
You can't return DONE or DECLINED. (If you find you need
to do that for some reason please contact me.)

See L<Apache2::Const/:http>
and L<Apache2::Controller::Refcard>.  You can also set
C<< status_line() >> or throw L<Apache2::Controller::X>
exceptions to be processed by an error template,
if you're using some form of template rendering - see
the section on errors below.

Add handlers in your config file with your own modules which 
C<use base> to inherit from these classes as you need them:

=head2 PerlHeaderParserHandler Apache2::Controller::Session

C<< $r->pnotes->{a2c}{session} >> automatically loaded from and 
stored to an L<Apache::Session> tied hash.  Pushes a PerlLogHandler
to save the session after the main controller returns OK.

See L<Apache2::Controller::Session>
and L<Apache2::Controller::Session::Cookie>.

=head2 PerlAuthenHandler Apache2::Controller::Authen::OpenID

Implements OpenID logins and redirects to your specified login 
controller by changing the dispatch selection on the fly.

See L<Apache2::Controller::Authen::OpenID>.

As for Access and Authz phases of AAA, you should
probably roll your own.  This framework isn't going
to dictate the means of your data storage or how
you organize your users.  See the mod_perl manual.

=head1 Apache2::Controller response phase handler

Apache2::Controller is set as the PerlResponseHandler if 
the dispatch class finds a valid module and method for the request.

=head2 Subclass L<Apache2::Request>

Most of the time you will want to use Apache2::Request as
a second base.  If you do this, then your controller
inherits the L<Apache2::RequestRec> methods with 
(some) modperl2 request extension libraries loaded during 
construction, or you can use others in the package namespace
and automatically get the methods.  

This way, you can call C<< $self->$methodname >> for any of
the methods associated with L<Apache2::Request>, 
L<Apache2::RequestRec> and some of their friends.  
Watch the log for warnings about redefined subroutines, or 
C<< use warnings FATAL => 'all' >> to keep yourself on the
right track.

To use a simplified example:

 package MyApp::C::SomeURIController;
 use base qw( 
     Apache2::Controller 
     Apache2::Request 
 );

 my %pats = (
     shipto => qr{ \A (.*?) \z }mxs,
     addr   => qr{ \A (.*?) \z }mxs,
     zip    => qr{ \A (\d{5}) \z }mxs,
 );
 
 sub set_shipping_address {
     my ($self) = @_;

     # $self->param() is Apache::Request param():
     my ($shipto, $addr, $zip) 
         = map {
             $self->param($_) =~ $pats{$_};
             $1 || return Apache2::Const::SERVER_ERROR;
         } qw( shipto addr zip );
     $self->content_type('text/plain');
     $self->print('Your package is on its way.');
     return Apache2::Const::HTTP_OK
 }

At any rate, your Apache2::Controller child object 
normally subclasses 
itself into Apache2::Request which magically
delegates all those methods
to the internal hash value C<< $self->{r} >>, which is the actual 
Apache2::Request object.
See L<Apache2::Request/SUBCLASSING Apache2::Request>
about those gory details.  

Whether 
you call C<< $self->$apache2_request_method >> or 
C<< $self->{r}->$apache2_request_method >> matters not,
you still ask the same object, so you might as well use
C<< $self->$method >> to make it look clean.

But, if you don't want to pollute your namespace of
potential URI handlers with the Apache2::Request* family
method namespace, don't use Apache2::Request as a base.
C<< $self->{r} >> is still an Apache2::Request object,
which gets you to all the RequestRec, RequestUtil,
RequestIO methods etc.

The rest of this manual assumes that you do use
L<Apache2::Request> as a base in your controller,
and refers to its methods via C<< $self >>.  Just
keep in mind that you don't have to, but can
access those methods via C<< $self->{r} >>.

=head1 RETURN VALUES

Your controller methods should use C<< eval { } >> if necessary and
act accordingly, set the right things for C<Apache2::RequestRec> 
and return the right HTTP constant.  See L<Apache2::Const/:http>
and L<Apache2::Controller::Refcard>.

In the event of an error, if you wish, use L<Apache2::Controller::X>
and throw one with field 'status' set to a valid HTTP return code.  
This lets you implement nice error templates if your controller uses 
L<Apache2::Controller::Render::Template> as a base.
See L<ERRORS> below.

Success in the controller method normally should just return the
appropriate HTTP status code.  You can return HTTP_OK (200) if that
is what you mean, or it is the default status if you return OK (0).

Or, if you do C<< $self->status( Apache2::Const::HTTP_SOMETHING ) >>
and then just C<< return() >>
or return OK (0), Apache2::Controller will not override the set status.

See L<Apache2::Controller::Refcard> for a list of HTTP return constants
and corresponding numbers and messages.

=head2 REDIRECTS, ETC.

As an example of return values, take browser redirects.
There's no need for an abstraction mechanism around redirects
since you have direct access to the Apache methods.

 package MyApp::Controller::Somewhere;
 use base qw( Apache2::Controller Apache2::Request );
 use Apache2::Const -compile => qw( REDIRECT );

 # maybe dispatched from http://myapp.xyz/somewhere/go_elsewhere
 sub go_elsewhere {
     my ($self, @path_args) = @_;
     $self->err_headers_out->add(Location => 'http://foo.bar');
     return Apache2::Const::REDIRECT;
 }

Keep in mind that if you use other request phase processors that
push a C<PerlLogHandler> like 
L<Apache2::Controller::DBI::Connector> or
L<Apache2::Controller::Session>, those will still run,
but for example the session controller won't save the session
if you set or return an http status higher than the HTTP_OK family
(HTTP_MULTIPLE_CHOICES (300) or higher.)

You should also not fiddle with the connection by causing
Apache2 to close it prematurely, else the post-response handlers 
may not run or won't run synchronously before another request 
is received that may have depended on their behavior.
(For example, you can't use a C<< PerlCleanupHandler >>
to do things like that because the request has already closed,
and it doesn't get processed before taking in the next request,
even when running in single-process mode.)

=head1 ERRORS

If you decide to set an error status code, you can print your
own content and return that status code.

If you want to use error templates, 
barf L<Apache2::Controller::X> objects.  These print a stack trace
to the error log at the WARN level of L<Log::Log4perl> from
this module's namespace.  If errors crop up from
other A2C request phase handlers, try setting
WARN log level for L<Apache2::Controller::NonResponseBase>
or L<Apache2::Controller::NonResponseRequest>.

Also see L<Apache2::Controller::Render::Template>.

You can use or subclass L<Apache2::Controller::X>,
to use C<< a2cx() >>,
or you can throw your own exception objects,
or just C<< die() >>, or C<< croak() >>,
or set C<< $self->status >>, headers etc., possibly printing content, 
or return the appropriate status from your controller method.

See L<Apache2::Controller::X> for help on throwing exceptions
with HTTP status, data dumps, etc.

If your code does break, die or throw an exception, this is 
caught by Apache2::Controller.  If your controller module implements
an C<<error() >> method, 
then C<< $handler->error() >> will be called passing the C<< $EVAL_ERROR >>
or exception object as the first argument.

 package MyApp::C::Foo;
 use YAML::Syck;
 # ...
 sub error {
     my ($self, $X) = @_;
     $self->status( Apache2::Const::HTTP_BAD_REQUEST );
     $self->content_type('text/plain');
     $self->print("Take this job and shove it!\n", "\n", $X, "\n");
     if ($X->isa('Apache2::Controller::X')) {
        # usually you wouldn't show gory details to the user...
        $self->print(Dump($X->dump)) if $X->dump;
        $self->print($X->trace) if $X->trace;  
     }
 }

For instance 
L<Apache2::Controller::Render::Template> implements
C<< error() >> for you, which looks for
the appropriately named error template as
F<template_dir/errors/###.html>.

Of course, all exceptions are sent to the error log using
L<Log::Log4perl> DEBUG() before the handler completes, and
any refusal status greater or equal to 400 (HTTP_BAD_REQUEST) 
will be written to the access log with L<Apache2::Log> log_reason() 
using the first few characters of the error.

See L<Apache2::Controller::Session/ERRORS> for how to control
whether or not a session is saved.  Usually it is automatically
saved, but not if you have an error.

C<< error() >> does not have to roll back DBI handles if you
use L<Apache2::Controller::DBI::Connector>, as this is
rolled back automatically in the C<< PerlLogHandler >>
phase if you don't commit the transaction.

=head1 CONTROLLER CLOSURES

Apache2::Controller's package space structure lets you take advantage
of closures that access variables in your controller subclass
package space, which are cached by modperl in child processes
across independent web requests.  Be careful with that and use
Devel::Size to keep memory usage down.  I have no idea how this
would work under threaded mpm.

=head1 CONTENT TYPE

Your controller should set content type with C<< $self->content_type() >>
to something specific if you need that.  Otherwise it will let
mod_perl set it to whatever it chooses when you start to print.
This is usually text/html.

=head1 LOGGING

Apache2::Controller uses L<Log::Log4perl>.  See that module

lib/Apache2/Controller.pm  view on Meta::CPAN


=cut

my %supports_error_method = ( );

sub handler : method {
    my ($class, $r) = @_;
    return $class if !defined $r;

    my $pnotes_a2c = $r->pnotes->{a2c} || { };

    my $method = $pnotes_a2c->{method};

    DEBUG("$class -> $method");

    my ($handler, $status, $X, $used_error_method_successfully) = ( );
    eval {

        $handler = $class->a2c_new($r);
        $method  = $handler->{method};

        DEBUG("executing $class -> $method()");
        my $args = $pnotes_a2c->{path_args} || [];
        $status = $handler->$method(@{$args});
        $status = $r->status() if !defined $status;

        if (defined $status) {
            if (ref $status || !looks_like_number($status)) {
                a2cx message => "Controller returned or set non-numeric status",
                    status  => Apache2::Const::SERVER_ERROR,
                    dump    => { controller_set_status => $status };
            }
            elsif ($status < 0) {
                a2cx message => "controller must set http status >= 0",
                    status  => Apache2::Const::SERVER_ERROR,
                    dump    => { controller_set_status => $status };
            }
        }
    };
    if ($X = $EVAL_ERROR) {

        my $ref = ref($X);
        my $blessed = $ref && blessed($X);

        my $error_method_status;

        # if appropriate and able to call self->error(), do that now
        if ($handler && !$pnotes_a2c->{use_standard_errors}) {

            eval {
                if (exists $supports_error_method{$class}) {
                    $error_method_status = $handler->error($X);
                } 
                elsif ($class->can('error')) {
                    $supports_error_method{$class} = 1;
                    $error_method_status = $handler->error($X); 
                }
                $used_error_method_successfully = 1;
            };

            # trap unknown errors that might have been thrown
            # by the error() subroutine
            $X = Exception::Class->caught('Apache2::Controller::X')
                || $EVAL_ERROR 
                || $X;
        }

        my $x_status = $ref && $blessed && $X->can('status')
            ? $X->status : undef;

        $status 
          = defined $x_status               ? $x_status
          : defined $error_method_status    ? $error_method_status
          : !defined $status                ? Apache2::Const::SERVER_ERROR
          : $status == Apache2::Const::OK   ? Apache2::Const::HTTP_OK
          : Apache2::Const::SERVER_ERROR
          ;

        WARN "Exception processing status: $status";

        if ($ref && $blessed) {
            WARN sub { "dump:\n"    .Dump($X->dump)     } if $X->can('dump');
            WARN sub { "data:\n"    .Dump($X->data)     } if $X->can('data');
            WARN sub { "trace:\n"   .Dump($X->trace)    } if $X->can('trace');
            WARN "$X";
        }
        else {
            WARN("Caught an unknown error: $X");
        }
    }

    DEBUG("done with handler processing...");
    DEBUG(sub {
        my $ctype = $r->content_type();
        "content type is ".($ctype || '[undef]');
    });
    
    $r->status($status) if $status;

    DEBUG(sub { 
        my $stat  = defined $status ? $status : '';
        my $sline = $r->status_line() || '[none]';
        my $smsg  
            = defined $status 
            ? (status_message($status) || '[no msg]') 
            : 'N/A';
        my $debugstatus = defined $status ? $status : '[status not defined]';
        "status: $debugstatus ($smsg); status_line='$sline'";
    });

    if (defined $status && $status >= Apache2::Const::HTTP_BAD_REQUEST) {
        # if status is an error, file error (possibly truncated) as a 
        # log_reason in the access log for why this request was denied.
        # (is this desirable?)
        log_bad_request_reason($r, $X);
    }

    if (!defined $status) {
        return Apache2::Const::OK;
    }
    elsif ($used_error_method_successfully) {



( run in 0.504 second using v1.01-cache-2.11-cpan-cdf2f3d4e48 )