NAME
MasonX::ApacheHandler::WithCallbacks - Execute code before Mason components
SYNOPSIS
In handler.pl:
use strict;
use MasonX::ApacheHandler::WithCallbacks;
sub calc_time {
my ($cbh, $args, $val, $key) = @_;
$args->{answer} = localtime($val || time);
}
my $ah = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => calc_time,
cb => \&calc_time } ]
);
sub handler {
my $r = shift;
$ah->handle_request($r);
}
In your component:
% if (exists $ARGS{answer}) {
<p><b>Answer: <% $ARGS{answer} %></b></p>
% } else {
<form>
<p>Enter an epoch time: <input type="text" name="epoch_time" /><br />
<input type="submit" name="myCallbacker|calc_time_cb" value="Calculate" />
</p>
</form>
% }
DESCRIPTION
MasonX::ApacheHandler::WithCallbacks subclasses HTML::Mason::ApacheHandler in order to provide callbacks. Callbacks are code references provided to the new()
constructor, and are triggered either for every request or by specially named keys in the Mason request arguments. The callbacks are executed at the beginning of a request, just before Mason creates a component stack and executes the components.
The idea is to configure Mason to execute arbitrary code before executing any components. Doing so 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 %ARGS
hash in components), and even to redirect or abort the request before Mason handles it.
JUSTIFICATION
Why would you want to do this? Well, there are a number of reasons. Some I can think of offhand include:
- Stricter separation of logic from presentation
-
Most application logic handled in Mason components takes place in
<%init>
blocks, often in the same component as presentation logic. By moving the application logic into subroutines in Perl modules and then directing Mason to execute those subroutines as callbacks, you obviously benefit from a cleaner separation of application logic and presentation. - Wigitization
-
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 Mason components. 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.
-
Callbacks are just Perl subroutines in modules loaded at server startup time. Thus the memory they consume is all in the parent, and then shared by the Apache children. 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
preloads
parameter to the HTML::Mason::Interp constructor). - Performance
-
Since callbacks are executed before Mason creates a component stack and executes the components, they 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.
And if those are enough reasons, then just consider this: Callbacks just way cool.
USAGE
MasonX::ApacheHandler::WithCallbacks supports two different types of callbacks: those triggered by a specially named key in the Mason request arguments hash, and those executed for every request.
Argument-Triggered Callbacks
Argument-triggered callbacks are triggered by specially named request arguments 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:
<input type="button" value="Save World" name="world|save_cb" />
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 MasonX::ApacheHandler::WithCallbacks will throw a HTML::Mason::Exception::Callback::InvalidKey exception. Here's how to configure such a callback when constructing your MasonX::ApacheHandler::WithCallbacks object so that that doesn't hapen:
my $cbh = MasonX::ApacheHandler::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 exectution of the &My::World::save
subroutine.
Callback Subroutines
The code references used for argument-triggered callbacks should accept four arguments, generally looking something like this:
sub foo {
my ($cbh, $args, $val, $key) = @_;
# Do stuff.
}
The arguments are as follows:
$cbh
-
The first argument is the MasonX::ApacheHandler::WithCallbacks object itself. Use its
redirect()
method to redirect the request to a new URL or theapache_req()
accessor to retrieve the Apache request object. $args
-
A reference to the Mason request arguments hash. This is the hash that will be used to create the
%ARGS
hash and the<%args>
block variables in your Mason components. Any changes you make to this hash will percolate back to your components. $val
-
The value of the callback trigger field. Although you may often be able to retrieve this value directly from the
$args
hash reference, if multiple callback keys point to the same subroutine or if the form overrode the priority, you may not be able to figure it out. So MasonX::ApacheHandler::WithCallbacks nicely passes in the value for you. $cb_key
-
The callback key that triggered the execution of the subroutine. In the example configuration above provided that the
My::World::save()
subroutine was triggered by a request argument, then the value of the$cb_key
argument would be "save".
Note that all callbacks are executed in a eval {}
block, so if any of your callback subroutines die
, MasonX::ApacheHandler::WithCallbacks will throw an HTML::Mason::Exception::Callback::Execution exception.
The Package Key
The use of the package key is a convenience so that a system with many callbacks can use callbacks with the same keys but in different packages. The idea is that the package key will uniquely identify the module in which each callback subroutine is found, but it doesn't necessarily have to be so. Use the package key any way you wish, or not at all:
my $cbh = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'save',
cb => \&My::World::save } ] );
But note that if you don't use the package key at all, you'll still need to provide one in the field to be submitted to the Mason server. By default, that key is "DEFAULT". Such a callback field in an HTML form would then look like this:
<input type="button" value="Save World" name="DEFAULT|save_cb" />
If you don't like the "DEFAULT" package name, you can set an alternative default using the default_pkg_name
parameter to new()
:
my $cbh = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'save',
cb => \&My::World::save } ],
default_pkg_name => 'MyPkg' );
Then, of course, any callbacks without a specified package key of their own will then use the custom default:
<input type="button" value="Save World" name="MyPkg|save_cb" />
Priority
Sometimes one callback is more important than anoether. For example, you might rely on the execution of one callback to set up variables needed by as a priority level seven callback another callback. Since you can't rely on the order in which callbacks are executed (the Mason request arguments are stored in a hash, and the processing of a hash is, of course, unordered), you need a method of ensuring that the setup callback executed first.
In such a case, you can set a higher priority level for the setup callback than for other callbacks:
my $cbh = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'setup',
priority => 3,
cb => \&setup },
{ cb_key => 'save',
cb => \&save }
] );
In this example, the "setup" callback has been configured with a priority level of "3". This ensures that it will always execute before the "save" callback, which has the default priority of "5". This is true regardless of the order of the fields in the corresponding HTML::Form:
<input type="button" value="Save World" name="DEFAULT|save_cb" />
<input type="hidden" name="DEFAULT|setup_cb" value="1" />
Despite the fact that the "setup" callback field appears after the "save" field (and will generally be submitted by the browser in that order), the "setup" callback will always execute first because of its higher priority.
Although the "save" callback got the default priority of "5", this too can be customized to a different priority level via the default_priority
parameter to new()
. For example, this configuration:
my $cbh = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'setup',
priority => 3,
cb => \&setup },
{ cb_key => 'save',
cb => \&save }
],
default_priority => 2 );
Will cause the "save" callback to always execute before the "setup" callback, since it's priority level will default to "2".
Conversely, the priority level can be overridden via the form submission field itself by appending a priority level to the end of the callback field name. Hence, this example:
<input type="button" value="Save World" name="DEFAULT|save_cb2" />
<input type="hidden" name="DEFAULT|setup_cb" value="1" />
causes the "save" callback to execute before the "setup" callback by overriding the "save" callback's priority to level "2". Of course, any other form field that triggers the "save" callback without a priority override will still execute "save" at its configured level.
Request Callbacks
Request callbacks come in two separate flavors: those that execute before the argument-triggered callbacks, and those that execute after the argument-triggered callbacks. These may be specified via the pre_callbacks
and post_callbacks
parameters to new()
, respectively:
my $cbh = MasonX::ApacheHandler::WithCallbacks->new
( pre_callbacks => [ \&translate, \&foobarate ],
post_callbacks => [ \&escape, \&negate ] );
In this example, the translate()
and foobarate()
subroutines will execute (in that order) before any argument-triggered callbacks are executed (none will be in this example, since none are specifed). Conversely, the escape()
and negate()
subroutines will be executed (in that order) after all argument-triggered callbacks have been executed. And regardless of what argument-triggered callbacks may be triggered, the request callbacks will always be executed for every request.
Although they may be used for different purposes, the pre_callbacks
and post_callbacks
callback code references expect the same arguments:
sub foo {
my ($cbh, $args) = @_;
}
Like the argument-triggered callbacks, the request callbacks get the MasonX::ApacheHandler::WithCallbacks object and the Mason request arguments hash. But since they're executed for every request (and there likely won't be many of them), they have no other arguments.
Also like the argument-triggered callbacks, request callbacks are executed in a eval {}
block, so if any of them die
s, an HTML::Mason::Exception::Callback::Execution exception will be thrown.
INTERFACE
Parameters To The new()
Constructor
In addition to those offered by the HTML::Mason::ApacheHandler base class, this module supports a number of parameters to the new()
constructor.
callbacks
-
Argument-triggered callbacks are configured via the
callbacks
parameter. This parameter is an array reference of hash references, and each hash reference specifies a single callback. The supported keys in the callback specification hashes are:cb_key
-
Required. A string that, when found in a properly-formatted Mason request argument key, will trigger the execution of the callback.
cb
-
Required. A reference to the Perl subroutine that will be executed when the
cb_key
has been found in a Mason request argument key. Each code reference should expect four arguments, the ApacheHandler::WithCallbacks object, the Mason request arguments hash reference, the value of the argument hash key that triggered the callback, and the callback key pointing to this code reference. Since this last argument will most often be equivalent tocb_key
, you can safely ignore it except in those cases where you might have more than one callback pointing to the same code reference. pkg_key
-
Optional. A key to uniquely identify the package in which the callback subroutine is found. This parameter is useful in systems with many callbacks, where developers may wish to use the same
cb_key
for different subroutines in different packages. The default package key may be set via thedefault_pkg_key
parameter. priority
-
Optional. Indicates the level of priority of a callback. Some callbacks are more important than others, and should be executed before others. MasonX::ApacheHandler::WithCallbacks supports priority levels, ranging from "0" (highest priority) to "9" (lowest priority). The default priority may be set via the
default_priority
parameter.
pre_callbacks
-
This parameter accepts an array reference of code references that should be executed for every request, before any other callbacks. Each code reference should expect two arguments: the ApacheHandler::WithCallbacks object and a reference to the Mason request arguments hash. Use this feature when you want to do something with the arguments sumitted for every request, such as convert character sets.
post_callbacks
-
This parameter accepts an array reference of code references that should be executed for every request, after all other callbacks have been called. Each code reference should expect two arguments: the ApacheHandler::WithCallbacks object and a reference to the Mason request arguments hash. Use this feature when you want to do something with the arguments sumitted for every request, such as HTML-escape their values.
default_priority
-
The priority level at which callbacks will be executed. This is the value that will be used for the
priority
key in each hash reference passed via thecallbacks
parameter tonew()
. You may specify a default priority level within the range of "0" (highst priority) to "9" (lowest priority). If not specified, it defaults to "5". default_pkg_key
-
The default package key for callbacks. This is the value that will be used for the
pkg_key
key in each hash referenced passed via thecallbacks
parameter tonew()
. It can be any string that evaluates to a true value, and defaults to "DEFAULT" if not specified.
Accessor Methods
The properties default_priority
and default_pkg_key
have standard read-only accessor methods of the same name. For example:
my $cbh = new HTML::Mason::ApacheHandler::WithCallbacks;
my $default_priority = $cbh->default_priority;
my $default_pkg_key = $cbh->default_pkg_key;
Other Methods
The ApacheHandler::WithCallbacks object has a few other publicly accessible methods.
apache_req
-
my $r = $cbh->apache_req;
Returns the Apache request object for the current request. If you've told Mason to use Apache::Request, it is the Apache::Request object that will be returned. Otherwise, if you're having CGI process your request arguments, then it will be the plain old Apache object.
redirect
-
$cbh->redirect($url); $cbh->redirect($url, $status); $cbh->redirect($url, $status, $wait);
Given a URL, this method generates a proper HTTP redirect for that URL. By default, the status code used is "302", but this can be overridden via the
$status
argument. If the optional$wait
argument is true, any callbacks scheduled to be executed after the call toredirect
will continue to be executed. In that clase,$cbh-
abort >> will not be called; rather, Mason will wait for the callbacks to finish running and then check the status and abort itself before creating a component stack or executing any components. If the$wait
argument is unspecified or false, then the request will be immediately terminated without executing subsequent callbacks. This approach relies on the execution of$cbh->abort
.Since by default
$cbh->redirect
calls$cbh->abort
, it will be trapped by aneval {}
block. If you are using aneval {}
block in your code to trap errors, you need to make sure to rethrow these exceptions, like this:eval { ... }; die $@ if $cbh->aborted; # handle other exceptions
redirected
-
$cbh->redirect($url) unless $cbh->redirected;
If the request has been redirected, this method returns the rediretion URL. Otherwise, it eturns false. This method is useful for conditions in which one callback has called
$cbh->redirect
with the optional$wait
argument set to a true value, thus allowing subsequent callbacks to continue to execute. If any of those subsequent callbacks want to call$cbh->redirect
themselves, they can check the value of$cbh->redirected
to make sure it hasn't been done already. abort
-
$cbh->abort($status);
Ends the current request without executing any more callbacks or any Mason components. The optional argument specifies the HTTP request status code to be returned to Apache.
abort
is implemented by throwing an HTML::Mason::Exception::Abort object and can thus be caught byeval()
. Theaborted
method is a shortcut for determining whether a caught error was generated byabort
. aborted
-
die $err if $cbh->aborted($err);
Returns true or
undef
indicating whether the specified$err
was generated byabort
. If no$err
was passed,aborted
examines$@
, instead.In this code, we catch and process fatal errors while letting
abort
exceptions pass through:eval { code_that_may_fail_or_abort() }; if ($@) { die $@ if $m->aborted; # handle fatal errors... }
$@
can lose its value quickly, so if you are planning to call$m->aborted
more than a few lines after the eval, you should save$@
to a temporary variable.
ACKNOWLEDGEMENTS
Garth Webb implemented the original callbacks in Bricolage, based on an idea he borrowed from Paul Lindner's work with Apache::ASP. My thanks to them both for planting this great idea!
BUGS
Please report all bugs via the CPAN Request Tracker at http://rt.cpan.org/NoAuth/Bugs.html?Dist=MasonX-ApacheHandler-WithCallbacks.
TODO
Add some good real-world examples to the documentation.
Maybe add a CallbackRequest object to pass into the callbacks as the sole argument instead of a bunch of invididual arguments?
Figure out how to use httpd.conf
PerlSetVar
directives to pass callback specs tonew()
.Maybe change
request_args()
to store callbacks in a hash instead of an array?Add tests for multiple packages supplying callbacks.
Add tests for error conditions.
Add tests for invalid parameters.
SEE ALSO
This module works with HTML::Mason by subclassing HTML::Mason::ApacheHandler. Inspired by the implementation of callbacks in Bricolage (http://bricolage.cc/), it is however a completely new code base with a rather different approach.
AUTHOR
David Wheeler <david@wheeler.net>
COPYRIGHT AND LICENSE
Copyright 2003 by David Wheeler
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.