NAME
MasonX::ApacheHandler::WithCallbacks - Functional and object-oriented Mason callback architecture
SYNOPSIS
In your Mason 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>
% }
In handler.pl:
use strict;
use MasonX::ApacheHandler::WithCallbacks;
sub calc_time {
my $cbh = shift;
my $args = $cbh->request_args;
my $val = $cbh->value;
$args->{answer} = localtime($val || time);
}
my $ah = MasonX::ApacheHandler::WithCallbacks->new
( 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 MasonX::CallbackHandler:
package MyApp::CallbackHandler;
use base qw(MasonX::CallbackHandler);
__PACKAGE__->register_subclass( class_key => 'myCallbacker' );
sub calc_time : Callback {
my $self = shift;
my $args = $self->request_args;
my $val = $cbh->value;
$args->{answer} = localtime($val || time);
}
And then, in handler.pl:
# Load order is important here!
use MyApp::CallbackHandler;
use MasonX::ApacheHandler::WithCallbacks;
my $ah = MasonX::ApacheHandler::WithCallbacks->new
( cb_classes => [qw(myCallbacker)] );
sub handler {
my $r = shift;
$ah->handle_request($r);
}
DESCRIPTION
MasonX::ApacheHandler::WithCallbacks subclasses HTML::Mason::ApacheHandler in order to provide a Mason callback system. Callbacks may be either code references provided to the new()
constructor, or methods defined in subclasses of MasonX::CallbackHandler. 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.
The idea behind this module is to provide a sort of plugin architecture for 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 %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 Perl modules and then directing Mason to execute that code as callbacks, you obviously benefit from a cleaner separation of application logic and presentation. - 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. 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 MasonX::CallbackHandler for an example solution for this very problem.
-
Callbacks are just Perl subroutines in modules loaded at server startup time. 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
preloads
parameter to the HTML::Mason::Interp constructor). - 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.
- 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. See MasonX::CallbackTester for details.
And if those aren't enough reasons, then just consider this: Callbacks are 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 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:
<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 a functional callback when constructing your MasonX::ApacheHandler::WithCallbacks object so that that doesn't happen:
my $cbah = 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 execution of the &My::World::save
subroutine.
Functional Callback Subroutines
Functional callbacks use a code reference for argument-triggered callbacks, and MasonX::ApacheHandler::WithCallbacks executes them with a single argument, a MasonX::CallbackHandler object. Thus, a callback subroutine will generally look something like this:
sub foo {
my $cbh = shift;
# Do stuff.
}
The MasonX::CallbackHandler object provides accessors to data relevant to the callback, including the callback key, the package key, and the request arguments. It also includes redirect()
and abort()
methods. See the MasonX::CallbackHandler documentation for all the goodies.
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.
Object-Oriented Callback Methods
Object-oriented callback methods are defined in subclasses of MasonX::CallbackHandler. Unlike functional callbacks, they are not called with a MasonX::CallbackHandler object, but with an instantiation of the callback subclass. These classes inherit all the goodies provided by MasonX::CallbackHandler, so you can essentially use their instances exactly as you would use the MasonX::CallbackHandler object in functional callback subroutines. But because they're subclasses, you can add your own methods and attributes. See MasonX::CallbackHandler 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 eval {}
block, so the same caveats apply.
Note: It's important that you use
any and all MasonX::Callback subclasses before you use MasonX::ApacheHandler::WithCallbacks
. This is to get around an issue with identifying the names of the callback methods in mod_perl. Read the comments in the MasonX::Callback source code if you're interested in learning more.
The Package Key
The use of the package key is a convenience so that a system with many functional 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 $cbah = 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 $cbah = 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" />
The Class Key
The class key is essentially a synonym for the package key, but applies more directly to object-oriented callbacks. The difference is mainly that it corresponds to an actual class, and that all MasonX::CallbackHandler subclasses are required to have a class key; it's not optional as it is with functional callbacks. The class key may be declared in your MasonX::CallbackHandler subclass like so:
package MyApp::CallbackHandler;
use base qw(MasonX::CallbackHandler);
__PACKAGE__->register_subclass( class_key => 'MyCBHandler' );
The class key can also be declared by implementing a CLASS_KEY()
method, like so:
package MyApp::CallbackHandler;
use base qw(MasonX::CallbackHandler);
__PACKAGE__->register_subclass;
use constant CLASS_KEY => 'MyCBHandler';
If no class key is explicitly defined, MasonX::CallbackHandler will use the subclass name, instead. In any event, the register_callback()
method must be called to register the subclass with MasonX::CallbackHandler. See the MasonX::CallbackHandler documentation for complete details.
Priority
Sometimes one callback is more important than another. For example, you might rely on the execution of one callback to set up variables needed by another. 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 executes first.
In such a case, you can set a higher priority level for the setup callback than for callbacks that depend on it. For functional callbacks, you can do it like this:
my $cbah = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'setup',
priority => 3,
cb => \&setup },
{ cb_key => 'save',
cb => \&save }
] );
For object-oriented callbacks, you can define the priority right in the callback method declaration:
sub setup : Callback( priority => 3 ) {
my $self = shift;
# ...
}
sub save : Callback {
my $self = shift;
# ...
}
In these examples, 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 functional callbacks and the default_priority
to the class declaration for object-oriented callbacks For example, this functional callback configuration:
my $cbah = MasonX::ApacheHandler::WithCallbacks->new
( callbacks => [ { cb_key => 'setup',
priority => 3,
cb => \&setup },
{ cb_key => 'save',
cb => \&save }
],
default_priority => 2 );
And this MasonX::CallbackHandler subclass declaration:
package MyApp::CallbackHandler;
use base qw(MasonX::CallbackHandler);
__PACKAGE__->register_subclass( class_key => 'MyCBHandler',
default_priority => 2 );
Will cause the "save" callback to always execute before the "setup" callback, since its priority level will default to "2".
In addition, 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. All of them execute before the Mason component stack executes. Functional request callbacks may be specified via the pre_callbacks
and post_callbacks
parameters to new()
, respectively:
my $cbah = MasonX::ApacheHandler::WithCallbacks->new
( pre_callbacks => [ \&translate, \&foobarate ],
post_callbacks => [ \&escape, \&negate ] );
Object-oriented request callbacks may be declared via the PreCallback
and PostCallback
method attributes, like so:
sub translate : PreCallback { ... }
sub foobarate : PreCallback { ... }
sub escape : PostCallback { ... }
sub negate : PostCallback { ... }
In these examples, the translate()
and foobarate()
subroutines or methods will execute (in that order) before any argument-triggered callbacks are executed (none will be in these examples, since none are specified).
Conversely, the escape()
and negate()
subroutines or methods 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
functional callback code references expect the same argument as argument-triggered functional callbacks: a MasonX::CallbackHandler object:
sub foo {
my $cbh = shift;
# Do your business here.
}
Similarly, object-oriented request callback methods will be passed an object of the class defined in the class key portion of the callback trigger -- either an object of the class in which the callback is defined, or an object of a subclass:
sub foo : PostCallback {
my $self = shift;
# ...
}
Of course, the attributes of the MasonX::CallbackHandler or subclass object will be different than in argument-triggered callbacks. For example, the priority
, pkg_key
, and cb_key
attributes will naturally be undefined. It will, however, be the same instance of the object passed to all other functional callbacks -- or to all other class callbacks with the same class key -- in a single request.
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 its own parameters to the new()
constructor. Each also has a corresponding httpd.conf variable, as well, so, if you really want to, you can use MasonX::ApacheHandler::WithCallbacks right in your httpd.conf file:
PerlModule MasonX::ApacheHandler::WithCallbacks
SetHandler perl-script
PerlHandler MasonX::ApacheHandler::WithCallbacks
The parameters to new()
and their corresponding httpd.conf variables are as follows:
callbacks
-
Argument-triggered functional 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 a single argument: a MasonX::CallbackHandler object. The same instance of a MasonX::CallbackHandler object will be used for all functional callbacks in a single request. 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 the others. MasonX::ApacheHandler::WithCallbacks supports priority levels ranging from "0" (highest priority) to "9" (lowest priority). The default priority for functional callbacks may be set via the
default_priority
parameter.
The <callbacks> parameter can also be specified via the httpd.conf configuration variable
MasonCallbacks
. UsePerlSetVar
to specify several callbacks; each one should be aneval
able string that converts into a hash reference as specified here. For example, to specify two callbacks, use this syntax:PerlAddVar MasonCallbacks "{ cb_key => 'foo', cb => sub { ... }" PerlAddVar MasonCallbacks "{ cb_key => 'bar', cb => sub { ... }"
Note that the
eval
able string must be entirely on its own line in the httpd.conf file. pre_callbacks
-
This parameter accepts an array reference of code references that should be executed for every request before any other callbacks. They will be executed in the order in which they're listed in the array reference. Each code reference should expect a single MasonX::CallbackHandler argument. The same instance of a MasonX::CallbackHandler object will be used for all functional callbacks in a single request. Use pre-argument-triggered request callbacks when you want to do something with the arguments submitted for every request, such as convert character sets.
The <pre_callbacks> parameter can also be specified via the httpd.conf configuration variable
MasonPreCallbacks
. Use multiplePerlAddVar
to add multiple pre-request callbacks; each one should be aneval
able string that converts into a code reference:PerlAddVar MasonPreCallbacks "sub { ... }" PerlAddVar MasonPreCallbacks "sub { ... }"
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. They will be executed in the order in which they're listed in the array reference. Each code reference should expect a single MasonX::CallbackHandler argument. The same instance of a MasonX::CallbackHandler object will be used for all functional callbacks in a single request. Use post-argument-triggered request callbacks when you want to do something with the arguments submitted for every request, such as HTML-escape their values.
The <post_callbacks> parameter can also be specified via the httpd.conf configuration variable
MasonPostCallbacks
. Use multiplePerlAddVar
to add multiple post-request callbacks; each one should be aneval
able string that converts into a code reference:PerlAddVar MasonPostCallbacks "sub { ... }" PerlAddVar MasonPostCallbacks "sub { ... }"
cb_classes
-
An array reference listing the class keys of all of the MasonX::CallbackHandler subclasses containing callback methods that you want included in your MasonX::ApacheHandler::WithCallbacks object. Alternatively, the
cb_classes
parameter may simply be the word "ALL", in which case all MasonX::CallbackHandler subclasses will have their callback methods registered with your MasonX::ApacheHandler::WithCallbacks object. See the MasonX::CallbackHandler documentation for details on creating callback classes and methods.Note: Be sure to
use MasonX::ApacheHandler::WithCallbacks
only after you'veuse
d all of the MasonX::CallbackHandler subclasses you need or else you won't be able to use their callback methods.The <cb_classes> parameter can also be specified via the httpd.conf configuration variable
MasonCbClasses
. Use multiplePerlAddVar
to add multiple callback class keys. But, again, be sure to load MasonX::ApacheHandler::WithCallbacks> only after you've loaded all of your MasonX::Callback handler subclasses:PerlModule My::CBClass PerlModule Your::CBClass PerlSetVar MasonCbClasses myCBClass PerlAddVar MasonCbClasses yourCBClass # Load MasonX::ApacheHandler::WithCallbacks last! PerlModule MasonX::ApacheHandler::WithCallbacks
default_priority
-
The priority level at which functional callbacks will be executed. Does not apply to object-oriented callbacks. This value will be used in each hash reference passed via the
callbacks
parameter tonew()
that lacks apriority
key. You may specify a default priority level within the range of "0" (highest priority) to "9" (lowest priority). If not specified, it defaults to "5".Use the
MasonDefaultPriority
variable to set the thedefault_priority
parameter in your httpd.conf file:PerlSetVar MasonDefaultPriority 3
default_pkg_key
-
The default package key for functional callbacks. Does not apply to object-oriented callbacks. This value that will be used in each hash reference passed via the
callbacks
parameter tonew()
that lacks apkg_key
key. It can be any string that evaluates to a true value, and defaults to "DEFAULT" if not specified.Use the
MasonDefaultPkgKey
variable to set the thedefault_pkg_key
parameter in your httpd.conf file:PerlSetVar MasonDefaultPkgKey CBFoo
Accessor Methods
The properties default_priority
and default_pkg_key
have standard read-only accessor methods of the same name. For example:
my $cbah = new HTML::Mason::ApacheHandler::WithCallbacks;
my $default_priority = $cbah->default_priority;
my $default_pkg_key = $cbah->default_pkg_key;
ACKNOWLEDGMENTS
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.
SEE ALSO
MasonX::CallbackHandler objects get passed as the sole argument to all functional callbacks, and offer access to data relevant to the callback. MasonX::CallbackHandler also defines the object-oriented callback interface, making its documentation a must-read for anyone who wishes to create callback classes and methods.
Use MasonX::CallbackTester to test your callback packages and classes.
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.