NAME¶
Params::Callback - Parameter callback base class
SYNOPSIS¶
Functional callback interface:
sub my_callback {
# Sole argument is a Params::Callback object.
my $cb = shift;
my $params = $cb->params;
my $value = $cb->value;
# Do stuff with above data.
}
Object-oriented callback interface:
package MyApp::Callback;
use base qw(Params::Callback);
use constant CLASS_KEY => 'MyHandler';
use strict;
sub my_callback : Callback {
my $self = shift;
my $params = $self->params;
my $value = $self->value;
# Do stuff with above data.
}
DESCRIPTION¶
Params::Callback provides the interface for callbacks to access parameter hashes
Params::CallbackRequest object, and callback metadata, as well as for
executing common request actions, such as aborting a callback execution
request. There are two ways to use Params::Callback: via functional-style
callback subroutines and via object-oriented callback methods.
For functional callbacks, a Params::Callback object is constructed by
Params::CallbackRequest for each call to its "request()" method, and
passed as the sole argument for every execution of a callback function. See
Params::CallbackRequest for details on how to create a Params::CallbackRequest
object to execute your callback code.
In the object-oriented callback interface, Params::Callback is the parent class
from which all callback classes inherit. Callback methods are declared in such
subclasses via "Callback", "PreCallback", and
"PostCallback" attributes to each method declaration. Methods and
subroutines declared without one of these callback attributes are not callback
methods, but normal methods or subroutines of the subclass. Read subclassing
for details on subclassing Params::Callback.
INTERFACE¶
Params::Callback provides the parameter hash accessors and utility methods that
will help manage a callback request (where a "callback request" is
considered a single call to the "request()" method on a
Params::CallbackRequest object). Functional callbacks always get a
Params::Callback object passed as their first argument; the same
Params::Callback object will be used for all callbacks in a single request.
For object-oriented callback methods, the first argument will of course always
be an object of the class corresponding to the class key used in the callback
key (or, for request callback methods, an instance of the class for which the
request callback method was loaded), and the same object will be reused for
all subsequent callbacks to the same class in a single request.
Accessor Methods¶
All of the Params::Callback accessor methods are read-only. Feel free to add
other attributes in your Params::Callback subclasses if you're using the
object-oriented callback interface.
cb_request
my $cb_request = $cb->cb_request;
Returns a reference to the Params::CallbackRequest object that executed the
callback.
params
my $params = $cb->params;
Returns a reference to the request parameters hash. Any changes you make to this
hash will propagate beyond the lifetime of the request.
apache_req
my $r = $cb->apache_req;
Returns the Apache request object for the current request, provided you've
passed one to "Params::CallbackRequest->request". This will be
most useful in a mod_perl environment, of course. Use Apache:FakeRequest in
tests to emmulate the behavior of an Apache request object.
requester
my $r = $cb->requester;
Returns the object that executed the callback by calling "request()"
on a Params::CallbackRequest object. Only available if the
"requester" parameter is passed to
"Params::CallbackRequest->request". This can be useful for
callbacks to get access to the object that executed the callbacks.
priority
my $priority = $cb->priority;
Returns the priority level at which the callback was executed. Possible values
range from "0" to "9", and may be set by a default
priority setting, by the callback configuration or method declaration, or by
the parameter callback trigger key. See Params::CallbackRequest for details.
cb_key
my $cb_key = $cb->cb_key;
Returns the callback key that triggered the execution of the callback. For
example, this callback-triggering parameter hash:
my $params = { "DEFAULT|save_cb" => 'Save' };
Will cause the "cb_key()" method in the relevant callback to return
"save".
pkg_key
my $pkg_key = $cb->pkg_key;
Returns the package key used in the callback trigger parameter key. For example,
this callback-triggering parameter hash:
my $params = { "MyCBs|save_cb" => 'Save' };
Will cause the "pkg_key()" method in the relevant callback to return
"MyCBs".
class_key
my $class_key = $cb->class_key;
An alias for "pkg_key", only perhaps a bit more appealing for use in
object-oriented callback methods.
trigger_key
my $trigger_key = $cb->trigger_key;
Returns the complete parameter key that triggered the callback. For example, if
the parameter key that triggered the callback looks like this:
my $params = { "MyCBs|save_cb6" => 'Save' };
Then the value returned by "trigger_key()" method will be
"MyCBs|save_cb6".
Note: Most browsers will submit "image" input fields with two
arguments, one with ".x" appended to its name, and the other with
".y" appended to its name. Because Params::CallbackRequest is
designed to be used with Web form fields populating a parameter hash, it will
ignore these fields and either use the field that's named without the
".x" or ".y", or create a field with that name and give it
a value of "1". The reasoning behind this approach is that the names
of the callback-triggering fields should be the same as the names that appear
in the HTML form fields. If you want the actual x and y image click
coordinates, access them directly from the request parameters:
my $params = $cb->params;
my $trigger_key = $cb->trigger_key;
my $x = $params->{"$trigger_key.x"};
my $y = $params->{"$trigger_key.y"};
value
my $value = $cb->value;
Returns the value of the parameter that triggered the callback. This value can
be anything that can be stored in a hash value -- that is, any scalar value.
Thus, in this example:
my $params = { "DEFAULT|save_cb" => 'Save',
"DEFAULT|open_cb" => [qw(one two)] };
"value()" will return the string "Save" in the save
callback, but the array reference "['one', 'two']" in the open
callback.
Although you may often be able to retrieve the value directly from the hash
reference returned by "params()", if multiple callback keys point to
the same subroutine or if the parameter that triggered the callback overrode
the priority, you may not be able to determine which value was submitted for a
particular callback execution. So Params::Callback kindly provides the value
for you. The exception to this rule is values submitted under keys named for
HTML "image" input fields. See the note about this under the
documentation for the "trigger_key()" method.
redirected
$cb->redirect($url) unless $cb->redirected;
If the request has been redirected, this method returns the redirection URL.
Otherwise, it returns false. This method is useful for conditions in which one
callback has called "$cb->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
"$cb->redirect" themselves, they can check the value of
"$cb->redirected" to make sure it hasn't been done already.
Other Methods¶
Params::Callback offers has a few other publicly accessible methods.
notes
$cb->notes($key => $value);
my $val = $cb->notes($key);
my $notes = $cb->notes;
Shortcut for "$cb->cb_request->notes". It provides a place to
store application data, giving developers a way to share data among multiple
callbacks. See "notes()" for more information.
redirect
$cb->redirect($url);
$cb->redirect($url, $wait);
$cb->redirect($url, $wait, $status);
This method can be used to redirect a request in a mod_perl environment,
provided that an Apache request object has been passed to
"Params::CallbackRequest->new". Outide of a mod_perl environment
or without an Apache request object, "redirect()" will still set the
proper value for the the "redirected()" method to return, and will
still abort the callback request.
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 to "redirect" will
continue to be executed. In that case, "$cb->abort" will not be
called; rather, Params::CallbackRequest will finish executing all remaining
callbacks and then return the abort status. If the $wait argument is
unspecified or false, then the request will be immediately terminated without
executing subsequent callbacks or. This approach relies on the execution of
"$cb->abort".
Since "$cb->redirect" calls "$cb->abort", it will be
trapped by an "eval {}" block. If you are using an "eval
{}" block in your code to trap exceptions, you need to make sure to
rethrow these exceptions, like this:
eval {
...
};
die $@ if $cb->aborted;
# handle other exceptions
abort
$cb->abort($status);
Aborts the current request without executing any more callbacks. The $status
argument specifies a request status code to be returned to by
"Params::CallbackRequest->request()".
"abort()" is implemented by throwing a
Params::Callback::Exception::Abort object and can thus be caught by
"eval{}". The "aborted()" method is a shortcut for
determining whether an exception was generated by "abort()".
aborted
die $err if $cb->aborted;
die $err if $cb->aborted($err);
Returns true or "undef" to indicate whether the specified $err was
generated by "abort()". If no $err argument is passed,
"aborted()" examines $@, instead.
In this code, we catch and process fatal errors while letting
"abort()" exceptions pass through:
eval { code_that_may_die_or_abort() };
if (my $err = $@) {
die $err if $cb->aborted($err);
# handle fatal errors...
}
$@ can lose its value quickly, so if you're planning to call
"$cb->aborted" more than a few lines after the "eval",
you should save $@ to a temporary variable and explicitly pass it to
"aborted()" as in the above example.
SUBCLASSING¶
Under Perl 5.6.0 and later, Params::Callback offers an object-oriented callback
interface. The object-oriented approach is to subclass Params::Callback, add
the callback methods you need, and specify a class key that uniquely
identifies your subclass across all Params::Callback subclasses in your
application. The key is to use Perl method attributes to identify methods as
callback methods, so that Params::Callback can find them and execute them when
the time comes. Here's an example:
package MyApp::CallbackHandler;
use base qw(Params::Callback);
use strict;
__PACKAGE__->register_subclass( class_key => 'MyHandler' );
sub build_utc_date : Callback( priority => 2 ) {
my $self = shift;
my $params = $self->params;
$params->{date} = sprintf "%04d-%02d-%02dT%02d:%02d:%02d",
delete @{$params}{qw(year month day hour minute second)};
}
This parameter-triggered callback can then be executed via a parameter hash such
as this:
my $params = { "MyHandler|build_utc_date_cb" => 1 };
Think of the part of the name preceding the pipe (the package key) as the class
name, and the part of the name after the pipe (the callback key) as the method
to call (plus '_cb'). If multiple parameters use the "MyHandler"
class key in a single request, then a single MyApp::CallbackHandler object
instance will be used to execute each of those callback methods for that
request.
To configure your Params::CallbackRequest object to use this callback, use its
"cb_classes" constructor parameter:
my $cb_request = Params::CallbackRequest->new
( cb_classes => [qw(MyHandler)] );
$cb_request->request($params);
Now, there are a few of things to note in the above callback class example. The
first is the call to "__PACKAGE__->register_subclass". This step
is
required in all callback subclasses in order that Params::Callback
will know about them, and thus they can be loaded into an instance of a
Params::CallbackRequest object via its "cb_classes" constructor
parameter.
Second, a callback class key
must be declared for the class. This can be
done either by implementing the "CLASS_KEY()" class method or
constant in your subclass, or by passing the "class_key" parameter
to "__PACKAGE__->register_subclass", which will then create the
"CLASS_KEY()" method for you. If no callback key is declared, then
Params::Callback will throw an exception when you try to load your subclass'
callback methods into a Params::CallbackRequest object.
One other, optional parameter, "default_priority", may also be passed
to "register_subclass()". The value of this parameter (an integer
between 0 and 9) will be used to create a "DEFAULT_PRIORITY()" class
method in the subclass. You can also explicitly implement the
"DEFAULT_PRIORITY()" class method or constant in the subclass, if
you'd rather. All parameter-triggered callback methods in that class will have
their priorities set to the value returned by "DEFAULT_PRIORITY()",
unless they override it via their "Callback" attributes.
And finally, notice the "Callback" attribute on the
"build_utc_date" method declaration in the example above. This
attribute is what identifies "build_utc_date" as a
parameter-triggered callback. Without the "Callback" attribute, any
subroutine declaration in your subclass will just be a subroutine or a method;
it won't be a callback, and it will never be executed by
Params::CallbackRequest. One parameter, "priority", can be passed
via the "Callback" attribute. In the above example, we pass
"priority => 2", which sets the priority for the callback.
Without the "priority" parameter, the callback's priority will be
set to the value returned by the "DEFAULT_PRIORITY()" class method.
Of course, the priority can still be overridden by adding it to the callback
trigger key. For example, here we force the callback priority for the
execution of the "build_utc_date" callback method for this one field
to be the highest priority, "0":
my $params = { "MyHandler|build_utc_date_cb0" => 1 };
Other parameters to the "Callback" attribute may be added in future
versions of Params::Callback.
Request callbacks can also be implemented as callback methods using the
"PreCallback" and "PostCallback" attributes, which
currently support no parameters.
Subclassing Examples¶
At this point, you may be wondering what advantage the object-oriented callback
interface offer over functional callbacks. There are a number of advantages.
First, it allows you to make use of callbacks provided by other users without
having to reinvent the wheel for yourself. Say someone has implemented the
above class with its exceptionally complex "build_utc_date()"
callback method. You need to have the same functionality, only with fractions
of a second added to the date format so that you can insert them into your
database without an error. (This is admittedly a contrived example, but you
get the idea.) To make it happen, you merely have to subclass the above class
and override the "build_utc_date()" method to do what you need:
package MyApp::Callback::Subclass;
use base qw(MyApp::CallbackHandler);
use strict;
__PACKAGE__->register_subclass;
# Implement CLASS_KEY ourselves.
use constant CLASS_KEY => 'SubHandler';
sub build_utc_date : Callback( priority => 1 ) {
my $self = shift;
$self->SUPER::build_utc_date;
my $params = $self->params;
$params->{date} .= '.000000';
}
This callback can then be triggered by a parameter hash such as this:
my $params = { "SubHandler|build_utc_date_cb" => 1 };
Note that we've used the "SubHandler" class key. If we used the
"MyHandler" class key, then the "build_utc_date()" method
would be called on an instance of the MyApp::CallbackHandler class, instead.
Request Callback Methods
I'll admit that the case for request callback methods is a bit more tenuous.
Granted, a given application may have 100s or even 1000s of
parameter-triggered callbacks, but only one or two request callbacks, if any.
But the advantage of request callback methods is that they encourage code
sharing, in that Params::Callback creates a kind of plug-in architecture Perl
templating architectures.
For example, say someone has kindly created a Params::Callback subclass,
Params::Callback::Unicodify, with the request callback method
"unicodify()", which translates character sets, allowing you to
always store data in the database in Unicode. That's all well and good, as far
as it goes, but let's say that you want to make sure that your Unicode strings
are actually encoded using the Perl "\x{..}" notation. Again, just
subclass:
package Params::Callback::Unicodify::PerlEncode;
use base qw(Params::Callback::Unicodify);
use strict;
__PACKAGE__->register_subclass( class_key => 'PerlEncode' );
sub unicodify : PreCallback {
my $self = shift;
$self->SUPER::unicodify;
my $params = $self->params;
encode_unicode($params); # Hand waving.
}
Now you can just tell Params::CallbackRequest to use your subclassed callback
handler:
my $cb_request = Params::CallbackRequest->new
( cb_classes => [qw(PerlEncode)] );
Yeah, okay, you could just create a second pre-callback request callback to
encode the Unicode characters using the Perl "\x{..}" notation. But
you get the idea. Better examples welcome.
Overriding the Constructor
Another advantage to using callback classes is that you can override the
Params::Callback "new()" constructor. Since every callback for a
single class will be executed on the same instance object in a single request,
you can set up object properties in the constructor that subsequent callback
methods in the same request can then access.
For example, say you had a series of pages that all do different things to
manage objects in your application. Each of those pages might have a number of
parameters in common to assist in constructing an object:
my $params = { class => "MyApp::Spring",
obj_id => 10,
# ...
};
Then the remaining parameters created for each of these pages have different
key/value pairs for doing different things with the object, perhaps with
numerous parameter-triggered callbacks. Here's where subclassing comes in
handy: you can override the constructor to construct the object when the
callback object is constructed, so that each of your callback methods doesn't
have to:
package MyApp::Callback;
use base qw(Params::Callback);
use strict;
__PACKAGE__->register_subclass( class_key => 'MyCBHandler' );
sub new {
my $class = shift;
my $self = $class->SUPER::new(@_);
my $params = $self->params;
$self->object($params->{class}->lookup( id => $params->{obj_id} ));
}
sub object {
my $self = shift;
if (@_) {
$self->{object} = shift;
}
return $self->{object};
}
sub save : Callback {
my $self = shift;
$self->object->save;
}
SUBCLASSING INTERFACE¶
Much of the interface for subclassing Params::Callback is evident in the above
examples. Here is a reference to the complete callback subclassing API.
Callback Class Declaration¶
Callback classes always subclass Params::Callback, so of course they must always
declare such. In addition, callback classes must always call
"__PACKAGE__->register_subclass" so that Params::Callback is
aware of them and can tell Params::CallbackRequest about them.
Second, callback classes
must have a class key. The class key can be
created either by implementing a "CLASS_KEY()" class method or
constant that returns the class key, or by passing the "class_key"
parameter to "register_subclass()" method. If no
"class_key" parameter is passed to "register_subclass()"
and no "CLASS_KEY()" method exists, "register_subclass()"
will create the "CLASS_KEY()" class method to return the actual
class name. So here are a few example callback class declarations:
package MyApp::Callback;
use base qw(Params::Callback);
__PACKAGE__->register_subclass( class_key => 'MyCBHandler' );
In this declaration "register_subclass()" will create a
"CLASS_KEY()" class method returning "MyCBHandler" in the
MyApp::CallbackHandler class.
package MyApp::AnotherCallback;
use base qw(MyApp::Callback);
__PACKAGE__->register_subclass;
use constant CLASS_KEY => 'AnotherCallback';
In this declaration, we've created an explicit "CLASS_KEY()" class
method (using the handy "use constant" syntax, so that
"register_subclass()" doesn't have to.
package MyApp::Callback::Foo;
use base qw(Params::Callback);
__PACKAGE__->register_subclass;
And in this callback class declaration, we've specified neither a
"class_key" parameter to "register_subclass()", nor
created a "CLASS_KEY()" class method. This causes
"register_subclass()" to create the "CLASS_KEY()" class
method returning the name of the class itself, i.e.,
"MyApp::FooHandler". Thus any parameter-triggered callbacks in this
class can be triggered by using the class name in the trigger key:
my $params = { "MyApp::Callback::Foo|take_action_cb" => 1 };
A second, optional parameter, "default_priority", may also be passed
to "register_subclass()" in order to set a default priority for all
of the methods in the class (and for all the methods in subclasses that don't
declare their own "default_priority"s):
package MyApp::Callback;
use base qw(Params::Callback);
__PACKAGE__->register_subclass( class_key => 'MyCB',
default_priority => 7 );
As with the "class_key" parameter, the "default_priority"
parameter creates a class method, "DEFAULT_PRIORITY()". If you'd
rather, you can create this class method yourself; just be sure that its value
is a valid priority -- that is, an integer between "0" and
"9":
package MyApp::Callback;
use base qw(Params::Callback);
use constant DEFAULT_PRIORITY => 7;
__PACKAGE__->register_subclass( class_key => 'MyCB' );
Any callback class that does not specify a default priority via the
"default_priority" or by implementing a <
DEFAULT_PRIORITY()> class method will simply inherit the priority
returned by "Params::Callback->DEFAULT_PRIORITY", which is
"5".
Note: In a mod_perl environment, it's important that you "use"
any and all Params::Callback subclasses
before you "use
Params::CallbackRequest". This is to get around an issue with identifying
the names of the callback methods in mod_perl. Read the comments in the source
code if you're interested in learning more.
Method Attributes¶
These method attributes are required to create callback methods in
Params::Callback subclasses.
Callback
sub take_action : Callback {
my $self = shift;
# Do stuff.
}
This attribute identifies a parameter-triggered callback method. The callback
key is the same as the method name ("take_action" in this example).
The priority for the callback may be set via an optional "priority"
parameter to the "Callback" attribute, like so:
sub take_action : Callback( priority => 5 ) {
my $self = shift;
# Do stuff.
}
Otherwise, the priority will be that returned by
"$self->DEFAULT_PRIORITY".
Note: The priority set via the "priority" parameter to the
"Callback" attribute is not inherited by any subclasses that
override the callback method. This may change in the future.
PreCallback
sub early_action : PreCallback {
my $self = shift;
# Do stuff.
}
This attribute identifies a method as a request callback that gets executed for
every request
before any parameter-triggered callbacks are executed .
No parameters to "PreCallback" are currently supported.
PostCallback
sub late_action : PostCallback {
my $self = shift;
# Do stuff.
}
This attribute identifies a method as a request callback that gets executed for
every request
after any parameter-triggered callbacks are executed . No
parameters to "PostCallback" are currently supported.
TODO¶
- •
- Allow methods that override parent methods to inherit the parent method's
priority?
SEE ALSO¶
Params::CallbackRequest constructs Params::Callback objects and executes the
appropriate callback functions and/or methods. It's worth a read.
SUPPORT¶
This module is stored in an open repository at the following address:
https://svn.kineticode.com/Params-CallbackRequest/trunk/
<
https://svn.kineticode.com/Params-CallbackRequest/trunk/>
Patches against Params::CallbackRequest are welcome. Please send bug reports to
<bug-params-callbackrequest@rt.cpan.org>.
AUTHOR¶
David E. Wheeler <david@justatheory.com>
COPYRIGHT AND LICENSE¶
Copyright 2003-2011 David E. Wheeler. Some Rights Reserved.
This library is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.