package MasonX::Interp::WithCallbacks;
use strict;
use HTML::Mason qw(1.23);
use HTML::Mason::Interp;
use HTML::Mason::Exceptions ();
use Params::CallbackRequest;
use vars qw($VERSION @ISA);
@ISA = qw(HTML::Mason::Interp);
$VERSION = '1.18';
Params::Validate::validation_options
( on_fail => sub { HTML::Mason::Exception::Params->throw( join '', @_ ) } );
use HTML::Mason::MethodMaker(
read_only => [qw(cb_request)],
read_write => [qw(comp_path)],
);
# We'll use this code reference to eval arguments passed in via httpd.conf
# PerlSetVar directives.
my $eval_directive = { convert => sub {
return 1 if ref $_[0]->[0];
for (@{$_[0]}) { $_ = eval $_ }
return 1;
}};
__PACKAGE__->valid_params
( default_priority =>
{ type => Params::Validate::SCALAR,
parse => 'string',
default => 5,
descr => 'Default callback priority'
},
default_pkg_key =>
{ type => Params::Validate::SCALAR,
parse => 'string',
default => 'DEFAULT',
descr => 'Default package key'
},
callbacks =>
{ type => Params::Validate::ARRAYREF,
parse => 'list',
optional => 1,
callbacks => $eval_directive,
descr => 'Callback specifications'
},
pre_callbacks =>
{ type => Params::Validate::ARRAYREF,
parse => 'list',
optional => 1,
callbacks => $eval_directive,
descr => 'Callbacks to be executed before argument callbacks'
},
post_callbacks =>
{ type => Params::Validate::ARRAYREF,
parse => 'list',
optional => 1,
callbacks => $eval_directive,
descr => 'Callbacks to be executed after argument callbacks'
},
cb_classes =>
{ type => Params::Validate::ARRAYREF | Params::Validate::SCALAR,
parse => 'list',
optional => 1,
descr => 'List of calback classes from which to load callbacks'
},
ignore_nulls =>
{ type => Params::Validate::BOOLEAN,
parse => 'boolean',
default => 0,
descr => 'Execute callbacks with null values'
},
cb_exception_handler =>
{ type => Params::Validate::CODEREF,
parse => 'code',
optional => 1,
descr => 'Callback execution exception handler'
},
);
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
# This causes everything to be validated twice, but it shouldn't matter
# much, since interp objects won't be created very often.
my $exh = delete $self->{cb_exception_handler};
$self->{cb_request} = Params::CallbackRequest->new
( leave_notes => 1,
($exh ? (exception_handler => $exh) : ()),
map { $self->{$_} ? ($_ => delete $self->{$_}) : () }
keys %{ __PACKAGE__->valid_params }
);
$self;
}
sub make_request {
my ($self, %p) = @_;
# We have to grab the parameters and copy them into a hash.
my %params = @{$p{args}};
$self->{comp_path} = $p{comp};
# Grab the apache request object, if it exists.
my $apache_req = $p{apache_req}
|| $self->delayed_object_params('request', 'apache_req')
|| $self->delayed_object_params('request', 'cgi_request');
# Execute the callbacks.
my $ret = $self->{cb_request}->request(
\%params,
requester => $self,
$apache_req ? ( apache_req => $apache_req ) : (),
);
# Abort the request if that's what the callbacks want.
unless (ref $ret) {
$self->{cb_request}->clear_notes;
HTML::Mason::Exception::Abort->throw(
error => 'Callback->abort was called',
aborted_value => $ret,
);
}
# Copy the parameters back -- too much copying!
$p{args} = [%params];
$p{comp} = $self->{comp_path};
# Get the request, copy the notes, and continue.
my $req = $self->SUPER::make_request(%p);
# Should I use the same reference?
%{$req->notes} = %{$self->{cb_request}->notes};
return $req;
}
# We override this method in order to clear out all the callback notes
# at the end of the Mason request.
sub purge_code_cache {
my $self = shift;
$self->{cb_request}->clear_notes;
$self->SUPER::purge_code_cache;
}
1;
__END__
=head1 NAME
MasonX::Interp::WithCallbacks - Mason callback support via Params::CallbackRequest.
=head1 SYNOPSIS
In your Mason component:
% if (exists $ARGS{answer}) {
Answer: <% $ARGS{answer} %>
% } else {
% }
In F:
use strict;
use MasonX::Interp::WithCallbacks;
sub calc_time {
my $cb = shift;
my $params = $cb->params;
my $val = $cb->value;
$params->{answer} = localtime($val || time);
}
my $ah = HTML::Mason::ApacheHandler->new
( interp_class => 'MasonX::Interp::WithCallbacks',
callbacks => [ { cb_key => 'calc_time',
pkg_key => 'myCallbacker',
cb => \&calc_time } ]
);
sub handler {
my $r = shift;
$ah->handle_request($r);
}
Or, in a subclass of Params::Callback:
package MyApp::CallbackHandler;
use base qw(Params::Callback);
__PACKAGE__->register_subclass( class_key => 'myCallbacker' );
sub calc_time : Callback {
my $self = shift;
my $params = $self->params;
my $val = $cb->value;
$params->{answer} = localtime($val || time);
}
And then, in F:
# Load order is important here!
use MyApp::CallbackHandler;
use MasonX::Interp::WithCallbacks;
my $ah = HTML::Mason::ApacheHandler->new
( interp_class => 'MasonX::Interp::WithCallbacks',
cb_classes => [qw(myCallbacker)] );
sub handler {
my $r = shift;
$ah->handle_request($r);
}
Or, just use MasonX::Interp::WithCallbacks directly:
use MyApp::CallbackHandler;
use MasonX::Interp::WithCallbacks;
my $interp = MasonX::Interp::WithCallbacks->new
( cb_classes => [qw(myCallbacker)] );
$interp->exec($comp, %args);
=begin comment
=head1 ABSTRACT
MasonX::Interp::WithCallbacks subclasses HTML::Mason::Interp in order to
provide functional and object-oriented callbacks via Params::CallbackRequest.
Callbacks are executed at the beginning of a request, just before Mason
creates and executes the request component stack.
=end comment
=head1 DESCRIPTION
MasonX::Interp::WithCallbacks subclasses HTML::Mason::Interp in order to
provide a Mason callback system built on
L. Callbacks may be either
code references provided to the C constructor, or methods defined in
subclasses of Params::Callback. Callbacks are triggered either for every
request or by specially named keys in the Mason request arguments, and all
callbacks are executed at the beginning of a request, just before Mason
creates and executes the request component stack.
This module brings support for a sort of plugin architecture based on
Params::CallbackRequest to Mason. Mason then executes code before executing
any components. This approach allows you to carry out logical processing of
data submitted from a form, to affect the contents of the Mason request
arguments (and thus the C<%ARGS> hash in components), and even to redirect or
abort the request before Mason handles it.
Much of the documentation here is based on that in
L, although it prefers using
HTML form fields for its examples rather than Perl hashes. But see the
Params::CallbackRequest documentation for the latest on its interface.
=head1 JUSTIFICATION
Why would you want to do this? Well, there are a number of reasons. Some I can
think of offhand include:
=over 4
=item Stricter separation of logic from presentation
Most application logic handled in Mason components takes place in
C<< <%init> >> blocks, often in the same component as presentation logic. By
moving the application logic into Perl modules and then directing Mason to
execute that code as callbacks, you obviously benefit from a cleaner
separation of application logic and presentation.
=item Widgitization
Thanks to their ability to preprocess arguments, callbacks enable developers
to develop easier-to-use, more dynamic widgets that can then be used in any
and all Mason component, or even with other templating systems. For example, a
widget that puts many related fields into a form (such as a date selection
widget) can have its fields preprocessed by a callback (for example, to
properly combine the fields into a unified date field) before the Mason
component that responds to the form submission gets the data. See
L for an example
solution for this very problem.
=item Shared Memory
Callbacks are just Perl subroutines in modules, and are therefore loaded at
server startup time in a mod_perl environment. Thus the memory they consume is
all in the Apache parent process, and shared by the child processes. For code
that executes frequently, this can be much less resource-intensive than code
in Mason components, since components are loaded separately in each Apache
child process (unless they're preloaded via the C parameter to the
HTML::Mason::Interp constructor).
=item Performance
Since they're executed before Mason creates a component stack and executes the
components, callbacks have the opportunity to short-circuit the Mason
processing by doing something else. A good example is redirection. Often the
application logic in callbacks does its thing and then redirects the user to a
different page. Executing the redirection in a callback eliminates a lot of
extraneous processing that would otherwise be executed before the redirection,
creating a snappier response for the user.
=item Testing
Mason components are not easy to test via a testing framework such as
Test::Harness. Subroutines in modules, on the other hand, are fully
testable. This means that you can write tests in your application test suite
to test your callback subroutines.
=back
And if those aren't enough reasons, then just consider this: Callbacks are
just I
=head1 USAGE
MasonX::Interp::WithCallbacks uses Params::CallbackRequest for its callback
architecture, and therefore supports its two different types of callbacks:
those triggered by a specially named key in the Mason request arguments hash,
and those executed for every request.
=head2 Argument-Triggered Callbacks
Argument-triggered callbacks are triggered by specially named request argument
keys. These keys are constructed as follows: The package name followed by a
pipe character ("|"), the callback key with the string "_cb" appended to it,
and finally an optional priority number at the end. For example, if you
specified a callback with the callback key "save" and the package key "world",
a callback field might be added to an HTML form like this:
This field, when submitted to the Mason server, would trigger the callback
associated with the "save" callback key in the "world" package. If such a
callback hasn't been configured, then Params::CallbackRequest will throw a
Params::CallbackReuest::Exception::InvalidKey exception. Here's how to
configure a functional callback when constructing your
MasonX::Interp::WithCallbacks object so that that doesn't happen:
my $interp = MasonX::Interp::WithCallbacks->new
( callbacks => [ { pkg_key => 'world',
cb_key => 'save',
cb => \&My::World::save } ] );
With this configuration, the request argument created by the above HTML form
field will trigger the execution of the C<&My::World::save> subroutine.
=head3 Functional Callback Subroutines
Functional callbacks use a code reference for argument-triggered callbacks,
and Params::CallbackRequest executes them with a single argument, a
Params::Callback object. Thus, a callback subroutine will generally look
something like this:
sub foo {
my $cb = shift;
# Do stuff.
}
The Params::Callback object provides accessors to data relevant to the
callback, including the callback key, the package key, and the request
arguments (or parameters). It also includes C and C
methods. See the L documentation for all
the goodies.
Note that all callbacks are executed in a C block, so if any of your
callback subroutines C, Params::CallbackRequest will throw an
Params::CallbackRequest::Exception::Execution exception If you don't like
this, use the C parameter to C to install your
own exception handler.
=head3 Object-Oriented Callback Methods
Object-oriented callback methods are defined in subclasses of
Params::Callback. Unlike functional callbacks, they are not called with a
Params::Callback object, but with an instance of the callback subclass. These
classes inherit all the goodies provided by Params::Callback, so you can
essentially use their instances exactly as you would use the Params::Callback
object in functional callback subroutines. But because they're subclasses, you
can add your own methods and attributes. See
L for all the gory details on subclassing,
along with a few examples. Generally, callback methods will look like this:
sub foo : Callback {
my $self = shift;
# Do stuff.
}
As with functional callback subroutines, method callbacks are executed in a
C block. Again, see the C parameter to install
your own exception handler.
B It's important that you C