Params::Callback(3pm)
π Params::Callback π
okay bestie, welcome to Params::Callback(3pm) from the User Contributed Perl Documentation section β¨ this is the base class for parameter callbacks and honestly? she's the backbone of the whole callback party π
β¨ NAME β¨
Params::Callback β the parameter callback base class, lovingly serving cunt since forever π
πΈ SYNOPSIS πΈ
so there's two whole vibes you can pick from, and you don't have to choose just one bestie, you can have both π«Ά
Functional callback interface β the little subroutine era β¨
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 β the full glam package π
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 hands you the interface for callbacks β that's how you get at the parameter hash, at the Params::CallbackRequest object, and at all the callback metadata π she also lets you do common request actions, like aborting a callback execution request (dramatic but sometimes necessary, no cap).
There are literally two ways to use her:
- functional-style callback subroutines
- object-oriented callback methods
For functional callbacks: a Params::Callback object gets constructed by Params::CallbackRequest every single time its request() method gets called, and that object is passed as the sole argument for every execution of a callback function. Want the deets on building a Params::CallbackRequest object to actually run your callback code? Go read Params::CallbackRequest, she's got you πΈ
In the object-oriented callback interface: Params::Callback is the parent class that all your callback classes inherit from. You declare callback methods inside those subclasses using the Callback, PreCallback, and PostCallback attributes on each method declaration β¨ methods and subroutines declared without one of these callback attributes are not callback methods β they're just normal methods or subroutines of the subclass, minding their own business π
want the full tea on subclassing? go read the subclassing section, babes.
π INTERFACE π
Params::Callback gives you the parameter hash accessors plus utility methods that help you manage a callback request β and just so we're clear, a "callback request" is one single call to the request() method on a Params::CallbackRequest object, periodt.
Functional callbacks always get a Params::Callback object passed as their first argument, and the same Params::Callback object gets 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 gets reused for all subsequent callbacks to the same class in a single request. It's giving efficiency, fr fr π
π Accessor Methods π
all of the Params::Callback accessor methods are read-only bestie, hands off π but if you're using the object-oriented callback interface, feel absolutely free to add other attributes in your Params::Callback subclasses β go off, customize, slay β¨
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. Heads up: any changes you make to this hash will propagate beyond the lifetime of the request, so be intentional okurrr π
apache_req
my $r = $cb->apache_req;
Returns the Apache request object for the current request β but only if you actually passed one to Params::CallbackRequest->request. This is gonna be most useful in a mod_perl environment, obviously. 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. Same energy, cuter name π
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 the trigger_key() method will be MyCBs|save_cb6 πΈ
Note: Most browsers will submitimageinput fields with two arguments β one with.xappended to its name, and the other with.yappended to its name. BecauseParams::CallbackRequestis 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.xor.y, or create a field with that name and give it a value of1. 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. So like, 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. Two different moods, same method π
And yeah, you may often be able to retrieve the value directly from the hash reference returned by params(), BUT 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, because she's thoughtful like that π«Ά 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 above.
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. Basically: vibe check before you double-redirect, bestie π
π« Other Methods π«
Params::Callback offers has a few other publicly accessible methods. Yes, more content, we're spoiled π
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. Iconic behavior, honestly π
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 β do not skip this part bestie, fr fr:
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(). She said β enough β
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->abortedmore than a few lines after theeval, you should save$@to a temporary variable and explicitly pass it toaborted()as in the above example. Do not be casual about this one, she will betray you π
β¨ SUBCLASSING β¨
Okay bestie, so here's the glow-up era. On Perl 5.6.0 and later, Params::Callback hands you an object-oriented callback interface. The OO way to do it: you subclass Params::Callback, drop in whatever callback methods you need, and declare a class key that uniquely identifies your subclass across all the Params::Callback subclasses in your application. Then the move is to use Perl method attributes to flag methods as callback methods, so Params::Callback can find them and run them when the time comes. Like, watch:
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)};
}
That parameter-triggered callback can then be executed via a parameter hash like this:
my $params = { "MyHandler|build_utc_date_cb" => 1 };
Think of the part of the name before the pipe (the package key) as the class name, and the part after the pipe (the callback key) as the method to call β plus '_cb' on the end, obviously. And here's the cute part: if multiple parameters use the "MyHandler" class key in a single request, then a single MyApp::CallbackHandler object instance gets used to execute every one of those callback methods for that request. One object, many callbacks, main character energy fr fr. π
To configure your Params::CallbackRequest object to use this callback, hit up its "cb_classes" constructor parameter:
my $cb_request = Params::CallbackRequest->new
( cb_classes => [qw(MyHandler)] );
$cb_request->request($params);
Now, there are a few things to clock in that callback class example above, and I need you to pay attention because they WILL come up. π«Ά
First: the call to "__PACKAGE__->register_subclass". This step is required in all callback subclasses β that's how Params::Callback knows they exist, and therefore how they can be loaded into an instance of a Params::CallbackRequest object via its "cb_classes" constructor parameter. No registration, no invite to the function. Periodt.
Second: a callback class key has to be declared for the class. You can do that 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. And if no callback key is declared at all? Params::Callback will throw an exception when you try to load your subclass' callback methods into a Params::CallbackRequest object. So like, declare it. π
One other, optional parameter, "default_priority", may also be passed to "register_subclass()". Its value β an integer between 0 and 9 β gets 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 do it yourself. All parameter-triggered callback methods in that class will have their priorities set to whatever "DEFAULT_PRIORITY()" returns, unless they override it via their "Callback" attributes.
And finally β notice that "Callback" attribute on the "build_utc_date" method declaration up there? That's the thing that identifies "build_utc_date" as a parameter-triggered callback. Without the "Callback" attribute, any subroutine declaration in your subclass is just... a subroutine. Or a method. It is not a callback and it will never be executed by Params::CallbackRequest. So sad, so plain. π
One parameter, "priority", can be passed via the "Callback" attribute. In the example above we pass "priority => 2", which sets the priority for that callback. If you skip the "priority" parameter, the callback's priority gets set to the value returned by the "DEFAULT_PRIORITY()" class method. And of course the priority can still be overridden by adding it right onto 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. So keep an eye out, bestie. π
Request callbacks can also be implemented as callback methods using the "PreCallback" and "PostCallback" attributes, which currently support no parameters.
πΈ Subclassing Examples πΈ
So at this point you might be sitting there like, "okay but what does the object-oriented callback interface actually give me over functional callbacks?" Valid question. There are a number of advantages, and honestly? She ate. π
First, it lets you make use of callbacks provided by other users without reinventing the wheel for yourself. Say someone has implemented that above class with its exceptionally complex "build_utc_date()" callback method. You need the same functionality, only with fractions of a second added to the date format so 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 };
And note β we used the "SubHandler" class key. If we'd used the "MyHandler" class key, then the "build_utc_date()" method would have been called on an instance of the MyApp::CallbackHandler class instead. Different girl, different vibe. β¨
π 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. Cute, right?
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, bestie:
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. And why would you want to do that, you ask? Because 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 that same request can then access. Chef's kiss. π
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 at the moment 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 β¨
okay bestie, much of the interface for subclassing Params::Callback is already visible in the examples above. Here's the complete reference to the callback subclassing API. π
π¦ Callback Class Declaration π¦
Callback classes always subclass Params::Callback, so of course they must always declare that. Plus, callback classes must always call __PACKAGE__->register_subclass so Params::Callback knows they exist 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 - passing the
class_keyparameter to theregister_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. (yes bestie, that's the class it says)
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_prioritys):
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 youuseany and allParams::Callbacksubclasses before youuse 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 thepriorityparameter to theCallbackattribute 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/
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.
And that's the whole vibe, bestie. This page came from Params::Callback(3pm), built for perl v5.36.0 and dated 2022-10-15. Stay iconic, keep your callbacks slaying. π
β¨
π¦ where this page comes from
- ubuntu noble: libparams-callbackrequest-perl 1.20-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libparams-callbackrequest-perl 1.20-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libparams-callbackrequest-perl 1.20-4 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms