The Application Module contains all the code specific to your application functionality, and it exists outside of your web server's document root, somewhere in the Perl library search path.

The Instance Script is what is actually called by your web server. It is a very small, simple file which simply creates an instance of your application and calls an inherited method, run(). Following is the entirety of "widgetview.cgi":

CGI::Application takes care of implementing the new() and the run() methods. Notice that at no point do you call print() to send any output to STDOUT. Instead, all output is returned as a scalar.

CGI::Application's most significant contribution is in managing the application state. Notice that all which is needed to push the application forward is to set the value of a HTML form parameter 'rm' to the value of the "run mode" you wish to handle the form submission. This is the key to CGI::Application.

ABSTRACT

The guiding philosophy behind CGI::Application is that a web-based application can be organized into a specific set of "Run Modes." Each Run Mode is roughly analogous to a single screen (a form, some output, etc.). All the Run Modes are managed by a single "Application Module" which is a Perl module. In your web server's document space there is an "Instance Script" which is called by the web server as a CGI (or an Apache::Registry script if you're using Apache + mod_perl).

This methodology is an inversion of the "Embedded" philosophy (ASP, JSP, EmbPerl, Mason, etc.) in which there are "pages" for each state of the application, and the page drives functionality. In CGI::Application, form follows function -- the Application Module drives pages, and the code for a single application is in one place; not spread out over multiple "pages". If you feel that Embedded architectures are confusing, unorganized, difficult to design and difficult to manage, CGI::Application is the methodology for you!

Apache is NOT a requirement for CGI::Application. Web applications based on CGI::Application will run equally well on NT/IIS or any other CGI-compatible environment. CGI::Application-based projects are, however, ripe for use on Apache/mod_perl servers, as they naturally encourage Good Programming Practices and will often work in persistent environments without modification.

DESCRIPTION

It is intended that your Application Module will be implemented as a sub-class of CGI::Application. This is done simply as follows:

package My::App;
use base 'CGI::Application';

Notation and Conventions

For the purpose of this document, we will refer to the following conventions:

WebApp.pm The Perl module which implements your Application Module class.
WebApp Your Application Module class; a sub-class of CGI::Application.
webapp.cgi The Instance Script which implements your Application Module.
$webapp An instance (object) of your Application Module class.
$c Same as $webapp, used in instance methods to pass around the
current object. (Sometimes referred as "$self" in other code)

Instance Script Methods

By inheriting from CGI::Application you have access to a number of built-in methods. The following are those which are expected to be called from your Instance Script.

new()

The new() method is the constructor for a CGI::Application. It returns a blessed reference to your Application Module package (class). Optionally, new() may take a set of parameters as key => value pairs:

TMPL_PATH - This optional parameter defines a path to a directory of templates. This is used by the load_tmpl() method (specified below), and may also be used for the same purpose by other template plugins. This run-time parameter allows you to further encapsulate instantiating templates, providing potential for more re-usability. It can be either a scalar or an array reference of multiple paths.

QUERY - This optional parameter allows you to specify an already-created CGI.pm query object. Under normal use, CGI::Application will instantiate its own CGI.pm query object. Under certain conditions, it might be useful to be able to use one which has already been created.

PARAMS - This parameter, if used, allows you to set a number of custom parameters at run-time. By passing in different values in different instance scripts which use the same application module you can achieve a higher level of re-usability. For instance, imagine an application module, "Mailform.pm". The application takes the contents of a HTML form and emails it to a specified recipient. You could have multiple instance scripts throughout your site which all use this "Mailform.pm" module, but which set different recipients or different forms.

One common use of instance scripts is to provide a path to a config file. This design allows you to define project wide configuration objects used by many several instance scripts. There are several plugins which simplify the syntax for this and provide lazy loading. Here's an example using CGI::Application::Plugin::ConfigAuto, which uses Config::Auto to support many configuration file formats.

See the list of of plugins below for more config file integration solutions.

run()

The run() method is called upon your Application Module object, from your Instance Script. When called, it executes the functionality in your Application Module.

my $webapp = WebApp->new();
$webapp->run();

This method first determines the application state by looking at the value of the CGI parameter specified by mode_param() (defaults to 'rm' for "Run Mode"), which is expected to contain the name of the mode of operation. If not specified, the state defaults to the value of start_mode().

Once the mode has been determined, run() looks at the dispatch table stored in run_modes() and finds the function pointer which is keyed from the mode name. If found, the function is called and the data returned is print()'ed to STDOUT and to the browser. If the specified mode is not found in the run_modes() table, run() will croak().

PSGI support

CGI::Application offers native PSGI support. The default query object for this is CGI::PSGI, which simply wrappers CGI.pm to provide PSGI support to it.

psgi_app()

$psgi_coderef = WebApp->psgi_app({ ... args to new() ... });

The simplest way to create and return a PSGI-compatible coderef. Pass in arguments to a hashref just as would to new. This returns a PSGI-compatible coderef, using CGI:::PSGI as the query object. To use a different query object, construct your own object using run_as_psgi(), as shown below.

It's possible that we'll change from CGI::PSGI to a different-but-compatible query object for PSGI support in the future, perhaps if CGI.pm adds native PSGI support.

run_as_psgi()

my $psgi_aref = $webapp->run_as_psgi;

Just like run, but prints no output and returns the data structure required by the PSGI specification. Use this if you want to run the application on top of a PSGI-compatible handler, such as Plack provides.

If you are just getting started, just use run(). It's easy to switch to using run_as_psgi later.

Why use run_as_psgi()? There are already solutions to run CGI::Application-based projects on several web servers with dozens of plugins. Running as a PSGI-compatible application provides the ability to run on additional PSGI-compatible servers, as well as providing access to all of the "Middleware" solutions available through the Plack project.

The structure returned is an arrayref, containing the status code, an arrayref of header key/values and an arrayref containing the body.

[ 200, [ 'Content-Type' => 'text/html' ], [ $body ] ]

By default the body is a single scalar, but plugins may modify this to return other value PSGI values. See "The Response" in PSGI for details about the response format.

Note that calling run_as_psgi only handles the output portion of the PSGI spec. to handle the input, you need to use a CGI.pm-like query object that is PSGI-compliant, such as CGI::PSGI. This query object must provide psgi_header and psgi_redirect methods.

However, often times all that needs to be in setup() is defining your run modes and your start mode. CGI::Application::Plugin::AutoRunmode allows you to do this with a simple syntax, using run mode attributes:

teardown()

If implemented, this method is called automatically after your application runs. It can be used to clean up after your operations. A typical use of the teardown() function is to disconnect a database connection which was established in the setup() function. You could also use the teardown() method to store state information about the application to the server.

cgiapp_init()

If implemented, this method is called automatically right before the setup() method is called. This method provides an optional initialization hook, which improves the object-oriented characteristics of CGI::Application. The cgiapp_init() method receives, as its parameters, all the arguments which were sent to the new() method.

An example of the benefits provided by utilizing this hook is creating a custom "application super-class" from which all your web applications would inherit, instead of CGI::Application.

By using CGI::Application and the cgiapp_init() method as illustrated, a suite of applications could be designed to share certain characteristics. This has the potential for much cleaner code built on object-oriented inheritance.

cgiapp_prerun()

If implemented, this method is called automatically right before the selected run mode method is called. This method provides an optional pre-runmode hook, which permits functionality to be added at the point right before the run mode method is called. To further leverage this hook, the value of the run mode is passed into cgiapp_prerun().

Another benefit provided by utilizing this hook is creating a custom "application super-class" from which all your web applications would inherit, instead of CGI::Application.

By using CGI::Application and the cgiapp_prerun() method as illustrated, a suite of applications could be designed to share certain characteristics. This has the potential for much cleaner code built on object-oriented inheritance.

It is also possible, within your cgiapp_prerun() method, to change the run mode of your application. This can be done via the prerun_mode() method, which is discussed elsewhere in this POD.

cgiapp_postrun()

If implemented, this hook will be called after the run mode method has returned its output, but before HTTP headers are generated. This will give you an opportunity to modify the body and headers before they are returned to the web browser.

A typical use for this hook is pipelining the output of a CGI-Application through a series of "filter" processors. For example:

* You want to enclose the output of all your CGI-Applications in
an HTML table in a larger page.
* Your run modes return structured data (such as XML), which you
want to transform using a standard mechanism (such as XSLT).
* You want to post-process CGI-App output through another system,
such as HTML::Mason.
* You want to modify HTTP headers in a particular way across all
run modes, based on particular criteria.

The cgiapp_postrun() hook receives a reference to the output from your run mode method, in addition to the CGI-App object. A typical cgiapp_postrun() method might be implemented as follows:

Obviously, with access to the CGI-App object you have full access to use all the methods normally available in a run mode. You could, for example, use load_tmpl() to replace the static HTML in this example with HTML::Template. You could change the HTTP headers (via header_type() and header_props() methods) to set up a redirect. You could also use the objects properties to apply changes only under certain circumstance, such as a in only certain run modes, and when a param() is a particular value.

cgiapp_get_query()

my $q = $webapp->cgiapp_get_query;

Override this method to retrieve the query object if you wish to use a different query interface instead of CGI.pm.

CGI.pm is only loaded if it is used on a given request.

If you can use an alternative to CGI.pm, it needs to have some compatibility with the CGI.pm API. For normal use, just having a compatible param method should be sufficient.

If you use the path_info option to the mode_param() method, then we will call the path_info() method on the query object.

If you use the Dump method in CGI::Application, we will call the Dump and escapeHTML methods on the query object.

Essential Application Methods

The following methods are inherited from CGI::Application, and are available to be called by your application within your Application Module. They are called essential because you will use all are most of them to get any application up and running. These functions are listed in alphabetical order.

load_tmpl()

This method takes the name of a template file, a reference to template data or a FILEHANDLE and returns an HTML::Template object. If the filename is undefined or missing, CGI::Application will default to trying to use the current run mode name, plus the extension ".html".

If you use the default template naming system, you should also use CGI::Application::Plugin::Forward, which simply helps to keep the current name accurate when you pass control from one run mode to another.

( For integration with other template systems and automated template names, see "Alternatives to load_tmpl() below. )

When you pass in a filename, the HTML::Template->new_file() constructor is used for create the object. When you pass in a reference to the template content, the HTML::Template->new_scalar_ref() constructor is used and when you pass in a filehandle, the HTML::Template->new_filehandle() constructor is used.

If tmpl_path() has been specified, load_tmpl() will set the HTML::Template path option to the path(s) provided. This further assists in encapsulating template usage.

The load_tmpl() method will pass any extra parameters sent to it directly to HTML::Template->new_file() (or new_scalar_ref() or new_filehandle()). This will allow the HTML::Template object to be further customized:

If your application requires more specialized behavior than this, you can always replace it by overriding load_tmpl() by implementing your own load_tmpl() in your CGI::Application sub-class application module.

This is a powerful technique because HTML::Template::Dumper loads and considers the template file that would actually be used. If the 'pet_name' token was missing in the template, the above test would fail. So, you are testing both your code and your templates in a much more precise way than using simple regular expressions to see if the string "Daisy" appeared somewhere on the page.

The load_tmpl() callback

Plugin authors will be interested to know that you can register a callback that will be executed just before load_tmpl() returns:

$self->add_callback('load_tmpl',\&your_method);

When your_method() is executed, it will be passed three arguments:

1. A hash reference of the extra params passed into C<load_tmpl>
2. Followed by a hash reference to template parameters.
With both of these, you can modify them by reference to affect
values that are actually passed to the new() and param() methods of the
template object.
3. The name of the template file.

The param() method enables a very valuable system for customizing your applications on a per-instance basis. One Application Module might be instantiated by different Instance Scripts. Each Instance Script might set different values for a set of parameters. This allows similar applications to share a common code-base, but behave differently. For example, imagine a mail form application with a single Application Module, but multiple Instance Scripts. Each Instance Script might specify a different recipient. Another example would be a web bulletin boards system. There could be multiple boards, each with a different topic and set of administrators.

The new() method provides a shortcut for specifying a number of run-time parameters at once. Internally, CGI::Application calls the param() method to set these properties. The param() method is a powerful tool for greatly increasing your application's re-usability.

query()

my $q = $webapp->query();
my $remote_user = $q->remote_user();

This method retrieves the CGI.pm query object which has been created by instantiating your Application Module. For details on usage of this query object, refer to CGI. CGI::Application is built on the CGI module. Generally speaking, you will want to become very familiar with CGI.pm, as you will use the query object whenever you want to interact with form data.

When the new() method is called, a CGI query object is automatically created. If, for some reason, you want to use your own CGI query object, the new() method supports passing in your existing query object on construction using the QUERY attribute.

There are a few rare situations where you want your own query object to be used after your Application Module has already been constructed. In that case you can pass it to c<query()> like this:

run_modes()

# The common usage: an arrayref of run mode names that exactly match subroutine names
$webapp->run_modes([qw/
form_display
form_process
/]);
# With a hashref, use a different name or a code ref
$webapp->run_modes(
'mode1' => 'some_sub_by_name',
'mode2' => \&some_other_sub_by_ref
);

This accessor/mutator specifies the dispatch table for the application states, using the syntax examples above. It returns the dispatch table as a hash.

The run_modes() method may be called more than once. Additional values passed into run_modes() will be added to the run modes table. In the case that an existing run mode is re-defined, the new value will override the existing value. This behavior might be useful for applications which are created via inheritance from another application, or some advanced application which modifies its own capabilities based on user input.

The run() method uses the data in this table to send the application to the correct function as determined by reading the CGI parameter specified by mode_param() (defaults to 'rm' for "Run Mode"). These functions are referred to as "run mode methods".

The hash table set by this method is expected to contain the mode name as a key. The value should be either a hard reference (a subref) to the run mode method which you want to be called when the application enters the specified run mode, or the name of the run mode method to be called:

The run mode method specified is expected to return a block of text (e.g.: HTML) which will eventually be sent back to the web browser. The run mode method may return its block of text as a scalar or a scalar-ref.

An advantage of specifying your run mode methods by name instead of by reference is that you can more easily create derivative applications using inheritance. For instance, if you have a new application which is exactly the same as an existing application with the exception of one run mode, you could simply inherit from that other application and override the run mode method which is different. If you specified your run mode method by reference, your child class would still use the function from the parent class.

An advantage of specifying your run mode methods by reference instead of by name is performance. Dereferencing a subref is faster than eval()-ing a code block. If run-time performance is a critical issue, specify your run mode methods by reference and not by name. The speed differences are generally small, however, so specifying by name is preferred.

Often, it makes good organizational sense to have your run modes map to methods of the same name. The array-ref interface provides a shortcut to that behavior while reducing verbosity of your code.

Note that another importance of specifying your run modes in either a hash or array-ref is to assure that only those Perl methods which are specifically designated may be called via your application. Application environments which don't specify allowed methods and disallow all others are insecure, potentially opening the door to allowing execution of arbitrary code. CGI::Application maintains a strict "default-deny" stance on all method invocation, thereby allowing secure applications to be built upon it.

IMPORTANT NOTE ABOUT RUN MODE METHODS

Your application should *NEVER* print() to STDOUT. Using print() to send output to STDOUT (including HTTP headers) is exclusively the domain of the inherited run() method. Breaking this rule is a common source of errors. If your program is erroneously sending content before your HTTP header, you are probably breaking this rule.

THE RUN MODE OF LAST RESORT: "AUTOLOAD"

If CGI::Application is asked to go to a run mode which doesn't exist it will usually croak() with errors. If this is not your desired behavior, it is possible to catch this exception by implementing a run mode with the reserved name "AUTOLOAD":

$self->run_modes(
"AUTOLOAD" => \&catch_my_exception
);

Before CGI::Application calls croak() it will check for the existence of a run mode called "AUTOLOAD". If specified, this run mode will in invoked just like a regular run mode, with one exception: It will receive, as an argument, the name of the run mode which invoked it:

This functionality could be used for a simple human-readable error screen, or for more sophisticated application behaviors.

start_mode()

$webapp->start_mode('mode1');

The start_mode contains the name of the mode as specified in the run_modes() table. Default mode is "start". The mode key specified here will be used whenever the value of the CGI form parameter specified by mode_param() is not defined. Generally, this is the first time your application is executed.

tmpl_path()

$webapp->tmpl_path('/path/to/some/templates/');

This access/mutator method sets the file path to the directory (or directories) where the templates are stored. It is used by load_tmpl() to find the template files, using HTML::Template's path option. To set the path you can either pass in a text scalar or an array reference of multiple paths.

More Application Methods

You can skip this section if you are just getting started.

The following additional methods are inherited from CGI::Application, and are available to be called by your application within your Application Module. These functions are listed in alphabetical order.

delete()

$webapp->delete('my_param');

The delete() method is used to delete a parameter that was previously stored inside of your application either by using the PARAMS hash that was passed in your call to new() or by a call to the param() method. This is similar to the delete() method of CGI.pm. It is useful if your application makes decisions based on the existence of certain params that may have been removed in previous sections of your app or simply to clean-up your param()s.

dump()

print STDERR $webapp->dump();

The dump() method is a debugging function which will return a chunk of text which contains all the environment and web form data of the request, formatted nicely for human readability. Useful for outputting to STDERR.

dump_html()

my $output = $webapp->dump_html();

The dump_html() method is a debugging function which will return a chunk of text which contains all the environment and web form data of the request, formatted nicely for human readability via a web browser. Useful for outputting to a browser.

error_mode()

$webapp->error_mode('my_error_rm');

If the runmode dies for whatever reason, run() will see if you have set a value for error_mode(). If you have, run() will call that method as a run mode, passing $@ as the only parameter.

Plugins authors will be interested to know that just before error_mode() is called, the error hook will be executed, with the error message passed in as the only parameter.

No error_mode is defined by default. The death of your error_mode() run mode is not trapped, so you can also use it to die in your own special way.

get_current_runmode()

$webapp->get_current_runmode();

The get_current_runmode() method will return a text scalar containing the name of the run mode which is currently being executed. If the run mode has not yet been determined, such as during setup(), this method will return undef.

header_add()

The header_add() method is used to add one or more headers to the outgoing response headers. The parameters will eventually be passed on to the CGI.pm header() method, so refer to the CGI docs for exact usage details.

Unlike calling header_props(), header_add() will preserve any existing headers. If a scalar value is passed to header_add() it will replace the existing value for that key.

If an array reference is passed as a value to header_add(), values in that array ref will be appended to any existing values values for that key. This is primarily useful for setting an additional cookie after one has already been set.

The header_props() method expects a hash of CGI.pm-compatible HTTP header properties. These properties will be passed directly to the header() or redirect() methods of the query() object. Refer to the docs of your query object for details. (Be default, it's CGI.pm).

Calling header_props with an empty hashref clobber any existing headers that have previously set.

header_props() returns a hash of all the headers that have currently been set. It can be called with no arguments just to get the hash current headers back.

To add additional headers later without clobbering the old ones, see header_add().

IMPORTANT NOTE REGARDING HTTP HEADERS

It is through the header_props() and header_add() method that you may modify the outgoing HTTP headers. This is necessary when you want to set a cookie, set the mime type to something other than "text/html", or perform a redirect. The header_props() method works in conjunction with the header_type() method. The value contained in header_type() determines if we use CGI::header() or CGI::redirect(). The content of header_props() is passed as an argument to whichever CGI.pm function is called.

Understanding this relationship is important if you wish to manipulate the HTTP header properly.

header_type()

$webapp->header_type('redirect');
$webapp->header_type('none');

This method used to declare that you are setting a redirection header, or that you want no header to be returned by the framework.

Setting the header to 'none' may be useful if you are streaming content. In other contexts, it may be more useful to set $ENV{CGI_APP_RETURN_ONLY} = 1;, which supresses all printing, including headers, and returns the output instead.

That's commonly used for testing, or when using CGI::Application as a controller for a cron script!

mode_param()

# Name the CGI form parameter that contains the run mode name.
# This is the the default behavior, and is often sufficient.
$webapp->mode_param('rm');
# Set the run mode name directly from a code ref
$webapp->mode_param(\&some_method);
# Alternate interface, which allows you to set the run
# mode name directly from $ENV{PATH_INFO}.
$webapp->mode_param(
path_info=> 1,
param =>'rm'
);

This accessor/mutator method is generally called in the setup() method. It is used to help determine the run mode to call. There are three options for calling it.

$webapp->mode_param('rm');

Here, a CGI form parameter is named that will contain the name of the run mode to use. This is the default behavior, with 'rm' being the parameter named used.

$webapp->mode_param(\&some_method);

Here a code reference is provided. It will return the name of the run mode to use directly. Example:

sub some_method {
my $self = shift;
return 'run_mode_x';
}

This would allow you to programmatically set the run mode based on arbitrary logic.

$webapp->mode_param(
path_info=> 1,
param =>'rm'
);

This syntax allows you to easily set the run mode from $ENV{PATH_INFO}. It will try to set the run mode from the first part of $ENV{PATH_INFO} (before the first "/"). To specify that you would rather get the run mode name from the 2nd part of $ENV{PATH_INFO}:

$webapp->mode_param( path_info=> 2 );

This also demonstrates that you don't need to pass in the param hash key. It will still default to rm.

You can also set path_info to a negative value. This works just like a negative list index: if it is -1 the run mode name will be taken from the last part of $ENV{PATH_INFO}, if it is -2, the one before that, and so on.

If no run mode is found in $ENV{PATH_INFO}, it will fall back to looking in the value of a the CGI form field defined with 'param', as described above. This allows you to use the convenient $ENV{PATH_INFO} trick most of the time, but also supports the edge cases, such as when you don't know what the run mode will be ahead of time and want to define it with JavaScript.

More about $ENV{PATH_INFO}.

Using $ENV{PATH_INFO} to name your run mode creates a clean separation between the form variables you submit and how you determine the processing run mode. It also creates URLs that are more search engine friendly. Let's look at an example form submission using this syntax:

Here the run mode would be set to "edit_form". Here's another example with a query string:

/cgi-bin/instance.cgi/edit_form?breed_id=2

This demonstrates that you can use $ENV{PATH_INFO} and a query string together without problems. $ENV{PATH_INFO} is defined as part of the CGI specification should be supported by any web server that supports CGI scripts.

prerun_mode()

$webapp->prerun_mode('new_run_mode');

The prerun_mode() method is an accessor/mutator which can be used within your cgiapp_prerun() method to change the run mode which is about to be executed. For example, consider:

In this example, the web user will be forced into the "login" run mode unless they have already logged in. The prerun_mode() method permits a scalar text string to be set which overrides whatever the run mode would otherwise be.

The use of prerun_mode() within cgiapp_prerun() differs from setting mode_param() to use a call-back via subroutine reference. It differs because cgiapp_prerun() allows you to selectively set the run mode based on some logic in your cgiapp_prerun() method. The call-back facility of mode_param() forces you to entirely replace CGI::Application's mechanism for determining the run mode with your own method. The prerun_mode() method should be used in cases where you want to use CGI::Application's normal run mode switching facility, but you want to make selective changes to the mode under specific conditions.

Note: The prerun_mode() method may ONLY be called in the context of a cgiapp_prerun() method. Your application will die() if you call prerun_mode() elsewhere, such as in setup() or a run mode method.

Dispatching Clean URIs to run modes

The process of mapping these URIs to run modes is called dispatching and is handled by CGI::Application::Dispatch. Dispatching is not required and is a layer you can fairly easily add to an application later.

Offline website development

You can work on your CGI::Application project on your desktop or laptop without installing a full-featured web-server like Apache. Instead, install CGI::Application::Server from CPAN. After a few minutes of setup, you'll have your own private application server up and running.

Automated Testing

There a couple of testing modules specifically made for CGI::Application.

Writing Plug-ins

Writing plug-ins is simple. Simply create a new package, and export the methods that you want to become part of a CGI::Application project. See CGI::Application::Plugin::ValidateRM for an example.

In order to avoid namespace conflicts within a CGI::Application object, plugin developers are recommended to use a unique prefix, such as the name of plugin package, when storing information. For instance:

Writing Advanced Plug-ins - Using callbacks

When writing a plug-in, you may want some action to happen automatically at a particular stage, such as setting up a database connection or initializing a session. By using these 'callback' methods, you can register a subroutine to run at a particular phase, accomplishing this goal.

Callback Examples

# register a callback to the standard CGI::Application hooks
# one of 'init', 'prerun', 'postrun', 'teardown' or 'load_tmpl'
# As a plug-in author, this is probably the only method you need.
# Class-based: callback will persist for all runs of the application
$class->add_callback('init', \&some_other_method);
# Object-based: callback will only last for lifetime of this object
$self->add_callback('prerun', \&some_method);
# If you want to create a new hook location in your application,
# You'll need to know about the following two methods to create
# the hook and call it.
# Create a new hook
$self->new_hook('pretemplate');
# Then later execute all the callbacks registered at this hook
$self->call_hook('pretemplate');

Callback Methods

add_callback()

The add_callback method allows you to register a callback function that is to be called at the given stage of execution. Valid hooks include 'init', 'prerun', 'postrun' and 'teardown', 'load_tmpl', and any other hooks defined using the new_hook method.

The callback should be a reference to a subroutine or the name of a method.

If multiple callbacks are added to the same hook, they will all be executed one after the other. The exact order depends on which class installed each callback, as described below under Callback Ordering.

Callbacks can either be object-based or class-based, depending upon whether you call add_callback as an object method or a class method:

Object-based callbacks are stored in your web application's $c object; at the end of the request when the $c object goes out of scope, the callbacks are gone too.

Object-based callbacks are useful for one-time tasks that apply only to the current running application. For instance you could install a teardown callback to trigger a long-running process to execute at the end of the current request, after all the HTML has been sent to the browser.

Class-based callbacks survive for the duration of the running Perl process. (In a persistent environment such as mod_perl or PersistentPerl, a single Perl process can serve many web requests.)

Class-based callbacks are useful for plugins to add features to all web applications.

Another feature of class-based callbacks is that your plugin can create hooks and add callbacks at any time - even before the web application's $c object has been initialized. A good place to do this is in your plugin's import subroutine:

Notice that $caller->add_callback installs the callback on behalf of the module that contained the line:

use CGI::Application::Plugin::MyPlugin;

new_hook(HOOK)

$self->new_hook('pretemplate');

The new_hook() method can be used to create a new location for developers to register callbacks. It takes one argument, a hook name. The hook location is created if it does not already exist. A true value is always returned.

call_hook(HOOK)

The call_hook method is used to executed the callbacks that have been registered at the given hook. It is used in conjunction with the new_hook method which allows you to create a new hook location.

The first argument to call_hook is the hook name. Any remaining arguments are passed to every callback executed at the hook location. So, a stub for a callback at the 'pretemplate' hook would look like this:

sub my_hook {
my ($c,@args) = @_;
# ....
}

Note that hooks are semi-public locations. Calling a hook means executing callbacks that were registered to that hook by the current object and also those registered by any of the current object's parent classes. See below for the exact ordering.

Callback Ordering

Object-based callbacks are run before class-based callbacks.

The order of class-based callbacks is determined by the inheritance tree of the running application. The built-in methods of cgiapp_init, cgiapp_prerun, cgiapp_postrun, and teardown are also executed this way, according to the ordering below.

In a persistent environment, there might be a lot of applications in memory at the same time. For instance:

If you have any questions, comments, bug reports or feature suggestions, post them to the support mailing list! To join the mailing list, simply send a blank message to "cgiapp-subscribe@lists.erlbaum.net".

IRC

You can also drop by #cgiapp on irc.perl.org with a good chance of finding some people involved with the project there.

SEE ALSO

CGI::Application::Framework - A full-featured web application based on CGI::Application. http://www.cafweb.org/

MORE READING

If you're interested in finding out more about CGI::Application, the following articles are available on Perl.com:

Using CGI::Application
http://www.perl.com/pub/a/2001/06/05/cgi.html
Rapid Website Development with CGI::Application
http://www.perl.com/pub/a/2006/10/19/cgi_application.html

Thanks to O'Reilly for publishing these articles, and for the incredible value they provide to the Perl community!

AUTHOR

Jesse Erlbaum <jesse@erlbaum.net>

Mark Stosberg has served as a co-maintainer since version 3.2, with the help of the numerous contributors documented in the Changes file.

CREDITS

CGI::Application was originally developed by The Erlbaum Group, a software engineering and consulting firm in New York City.

Thanks to Vanguard Media (http://www.vm.com) for funding the initial development of this library and for encouraging Jesse Erlbaum to release it to the world.

Many thanks to Sam Tregar (author of the most excellent HTML::Template module!) for his innumerable contributions to this module over the years, and most of all for getting me off my ass to finally get this thing up on CPAN!

Many other people have contributed specific suggestions or patches, which are documented in the Changes file.

Thanks also to all the members of the CGI-App mailing list! Your ideas, suggestions, insights (and criticism!) have helped shape this module immeasurably. (To join the mailing list, simply send a blank message to "cgiapp-subscribe@lists.erlbaum.net".)

LICENSE

This module is free software; you can redistribute it and/or modify it under the terms of either:

a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version,

or

b) the "Artistic License" which comes with this module.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details.

You should have received a copy of the Artistic License with this module, in the file ARTISTIC. If not, I'll be glad to provide one.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA