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 \*(C`request()\*(C' 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 \*(C`Callback\*(C', \*(C`PreCallback\*(C', and \*(C`PostCallback\*(C' 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 \*(L"callback request\*(R" is considered a single call to the \*(C`request()\*(C' 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 \*(C`Params::CallbackRequest->request\*(C'. 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 \*(C`request()\*(C' on a Params::CallbackRequest object. Only available if the \*(C`requester\*(C' parameter is passed to \*(C`Params::CallbackRequest->request\*(C'. 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 \*(L"0\*(R" to \*(L"9\*(R", 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 \*(C`cb_key()\*(C' method in the relevant callback to return \*(L"save\*(R".

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 \*(C`pkg_key()\*(C' method in the relevant callback to return \*(L"MyCBs\*(R".

class_key

my $class_key = $cb->class_key;

An alias for \*(C`pkg_key\*(C', 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 \*(C`trigger_key()\*(C' method will be \*(L"MyCBs|save_cb6\*(R".

Note: Most browsers will submit \*(L"image\*(R" input fields with two arguments, one with \*(L".x\*(R" appended to its name, and the other with \*(L".y\*(R" 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 \*(L".x\*(R" or \*(L".y\*(R", or create a field with that name and give it a value of \*(L"1\*(R". 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 \s-1HTML\s0 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)] };

\*(C`value()\*(C' will return the string \*(L"Save\*(R" in the save callback, but the array reference \*(C`['one', 'two']\*(C' in the open callback.

Although you may often be able to retrieve the value directly from the hash reference returned by \*(C`params()\*(C', 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 \s-1HTML\s0 \*(L"image\*(R" input fields. See the note about this under the documentation for the \*(C`trigger_key()\*(C' method.

redirected

$cb->redirect($url) unless $cb->redirected;

If the request has been redirected, this method returns the redirection \s-1URL\s0. Otherwise, it returns false. This method is useful for conditions in which one callback has called \*(C`$cb->redirect\*(C' 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 \*(C`$cb->redirect\*(C' themselves, they can check the value of \*(C`$cb->redirected\*(C' 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 \*(C`$cb->cb_request->notes\*(C'. It provides a place to store application data, giving developers a way to share data among multiple callbacks. See \*(C`notes()\*(C' 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 \*(C`Params::CallbackRequest->new\*(C'. Outide of a mod_perl environment or without an Apache request object, \*(C`redirect()\*(C' will still set the proper value for the the \*(C`redirected()\*(C' method to return, and will still abort the callback request.

Given a \s-1URL\s0, this method generates a proper \s-1HTTP\s0 redirect for that \s-1URL\s0. By default, the status code used is \*(L"302\*(R", 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 \*(C`redirect\*(C' will continue to be executed. In that case, \*(C`$cb->abort\*(C' 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 \*(C`$cb->abort\*(C'.

Since \*(C`$cb->redirect\*(C' calls \*(C`$cb->abort\*(C', it will be trapped by an \*(C`eval {}\*(C' block. If you are using an \*(C`eval {}\*(C' 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 \*(C`Params::CallbackRequest->request()\*(C'.

\*(C`abort()\*(C' is implemented by throwing a Params::Callback::Exception::Abort object and can thus be caught by \*(C`eval{}\*(C'. The \*(C`aborted()\*(C' method is a shortcut for determining whether an exception was generated by \*(C`abort()\*(C'.

aborted

die $err if $cb->aborted; die $err if $cb->aborted($err);

Returns true or \*(C`undef\*(C' to indicate whether the specified $err was generated by \*(C`abort()\*(C'. If no $err argument is passed, \*(C`aborted()\*(C' examines $@, instead.

In this code, we catch and process fatal errors while letting \*(C`abort()\*(C' 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 \*(C`$cb->aborted\*(C' more than a few lines after the \*(C`eval\*(C', you should save $@ to a temporary variable and explicitly pass it to \*(C`aborted()\*(C' 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 \*(L"MyHandler\*(R" 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 \*(C`cb_classes\*(C' 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 \*(C`_\|_PACKAGE_\|_->register_subclass\*(C'. 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 \*(C`cb_classes\*(C' constructor parameter.

Second, a callback class key must be declared for the class. This can be done either by implementing the \*(C`CLASS_KEY()\*(C' class method or constant in your subclass, or by passing the \*(C`class_key\*(C' parameter to \*(C`_\|_PACKAGE_\|_->register_subclass\*(C', which will then create the \*(C`CLASS_KEY()\*(C' 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, \*(C`default_priority\*(C', may also be passed to \*(C`register_subclass()\*(C'. The value of this parameter (an integer between 0 and 9) will be used to create a \*(C`DEFAULT_PRIORITY()\*(C' class method in the subclass. You can also explicitly implement the \*(C`DEFAULT_PRIORITY()\*(C' 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 \*(C`DEFAULT_PRIORITY()\*(C', unless they override it via their \*(C`Callback\*(C' attributes.

And finally, notice the \*(C`Callback\*(C' attribute on the \*(C`build_utc_date\*(C' method declaration in the example above. This attribute is what identifies \*(C`build_utc_date\*(C' as a parameter-triggered callback. Without the \*(C`Callback\*(C' 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, \*(C`priority\*(C', can be passed via the \*(C`Callback\*(C' attribute. In the above example, we pass \*(C`priority => 2\*(C', which sets the priority for the callback. Without the \*(C`priority\*(C' parameter, the callback's priority will be set to the value returned by the \*(C`DEFAULT_PRIORITY()\*(C' 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 \*(C`build_utc_date\*(C' callback method for this one field to be the highest priority, \*(L"0\*(R":

my $params = { "MyHandler|build_utc_date_cb0" => 1 };

Other parameters to the \*(C`Callback\*(C' attribute may be added in future versions of Params::Callback.

Request callbacks can also be implemented as callback methods using the \*(C`PreCallback\*(C' and \*(C`PostCallback\*(C' 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 \*(C`build_utc_date()\*(C' 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 \*(C`build_utc_date()\*(C' 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 \*(L"SubHandler\*(R" class key. If we used the \*(L"MyHandler\*(R" class key, then the \*(C`build_utc_date()\*(C' 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 \*(C`unicodify()\*(C', 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 \*(C`\x{..}\*(C' 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 \*(C`\x{..}\*(C' 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 \*(C`new()\*(C' 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 \s-1API\s0.

Callback Class Declaration

Callback classes always subclass Params::Callback, so of course they must always declare such. In addition, callback classes must always call \*(C`_\|_PACKAGE_\|_->register_subclass\*(C' 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 \*(C`CLASS_KEY()\*(C' class method or constant that returns the class key, or by passing the \*(C`class_key\*(C' parameter to \*(C`register_subclass()\*(C' method. If no \*(C`class_key\*(C' parameter is passed to \*(C`register_subclass()\*(C' and no \*(C`CLASS_KEY()\*(C' method exists, \*(C`register_subclass()\*(C' will create the \*(C`CLASS_KEY()\*(C' 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 \*(C`register_subclass()\*(C' will create a \*(C`CLASS_KEY()\*(C' class method returning \*(L"MyCBHandler\*(R" 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 \*(C`CLASS_KEY()\*(C' class method (using the handy \*(C`use constant\*(C' syntax, so that \*(C`register_subclass()\*(C' 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 \*(C`class_key\*(C' parameter to \*(C`register_subclass()\*(C', nor created a \*(C`CLASS_KEY()\*(C' class method. This causes \*(C`register_subclass()\*(C' to create the \*(C`CLASS_KEY()\*(C' class method returning the name of the class itself, i.e., \*(L"MyApp::FooHandler\*(R". 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, \*(C`default_priority\*(C', may also be passed to \*(C`register_subclass()\*(C' 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 \*(C`default_priority\*(C's):

package MyApp::Callback; use base qw(Params::Callback); _\|_PACKAGE_\|_->register_subclass( class_key => 'MyCB', default_priority => 7 );

As with the \*(C`class_key\*(C' parameter, the \*(C`default_priority\*(C' parameter creates a class method, \*(C`DEFAULT_PRIORITY()\*(C'. 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 \*(L"0\*(R" and \*(L"9\*(R":

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 \*(C`default_priority\*(C' or by implementing a <\s-1DEFAULT_PRIORITY\s0()> class method will simply inherit the priority returned by \*(C`Params::Callback->DEFAULT_PRIORITY\*(C', which is \*(L"5\*(R".

Note: In a mod_perl environment, it's important that you \*(C`use\*(C' any and all Params::Callback subclasses before you \*(C`use Params::CallbackRequest\*(C'. 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 (\*(L"take_action\*(R" in this example). The priority for the callback may be set via an optional \*(C`priority\*(C' parameter to the \*(C`Callback\*(C' attribute, like so:

sub take_action : Callback( priority => 5 ) { my $self = shift; # Do stuff. }

Otherwise, the priority will be that returned by \*(C`$self->DEFAULT_PRIORITY\*(C'.

Note: The priority set via the \*(C`priority\*(C' parameter to the \*(C`Callback\*(C' 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 \*(C`PreCallback\*(C' 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 \*(C`PostCallback\*(C' are currently supported.

TODO

  • Allow methods that override parent methods to inherit the parent method's priority?

RELATED TO Params::Callback…

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 <[email protected]>.

AUTHOR

David E. Wheeler <[email protected]>

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.