CGI::Application is intended to make it easier to create sophisticated, reusable web-based applications. This module implements a methodology which, if followed, will make your web software easier to design, easier to document, easier to write, and easier to evolve.

CGI::Application builds on standard, non-proprietary technologies and techniques, such as the Common Gateway Interface and Lincoln D. Stein's excellent CGI.pm module. CGI::Application judiciously avoids employing technologies and techniques which would bind a developer to any one set of tools, operating system or web server.

Following is an example of the typical usage of CGI::Application.

Imagine you have to write an application to search through a database of widgets. Your application has three screens:

1. Search form
2. List of results
3. Detail of a single record

To write this application using CGI::Application you will create two files:

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.

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 applications are, however, ripe for use on Apache/mod_perl servers, as they naturally encourage Good Programming Practices. As always, use strict!

CGI::Application is an Object-Oriented Perl module which implements an Abstract Class. It is not intended that this package be instantiated directly. Instead, it is intended that your Application Module will be implemented as a Sub-Class of CGI::Application.

To inherit from CGI::Application, the following code should go at the beginning of your Application Module, after your package declaration:

use base 'CGI::Application';

Notation and Conventions

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

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 adds value to the load_tmpl() method (specified below). This sets a path using HTML::Template's path option when you call load_tmpl() to get your HTML::Template object. This run-time parameter allows you to further encapsulate instantiating templates, providing potential for more reusability.

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 reusability. 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.

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.

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().

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.

If implemented, this method is called automatically right before the setup() method is called. This method provides an optional initalization 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 which all your CGI 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.

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 CGI 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.

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

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

The header_props() method expects a hash of CGI.pm-compatible HTTP header properties. These properties will be passed directly to CGI.pm's header() or redirect() methods. Refer to CGI for usage details.

IMPORTANT NOTE REGARDING HTTP HEADERS

It is through the header_props() 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.

The header_type() method expects to be passed either 'header' or 'redirect'. This method specifies the type of HTTP headers which should be sent back to the browser. If not specified, defaults is 'header'. See the header section of CGI for details.

This method takes the name of a template file and returns an HTML::Template object. The HTML::Template->new_file() constructor is used for create the object. Refer to HTML::Template for specific usage of HTML::Template.

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

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

This accessor/mutator method is generally called in the setup() method. The mode_param() method sets the name of the CGI form parameter which contains the run mode of the application. If not specified, the default value is 'rm'. This CGI parameter is queried by the run() method to send the program to the correct mode.

Alternatively you can set mode_param() to use a call-back via subroutine reference:

$webapp->mode_param(\&some_method);

This would allow you to create an instance method whose output would be used as the value of the current run-mode. E.g., a "mode param method":

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

This would allow you to programmatically set the run-mode based on something besides the value of a CGI parameter -- $ENV{PATH_INFO}, for example.

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 reusability.

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.

This accessor/mutator expects a hash which specifies the dispatch table for the different CGI states. The run() method uses the data in this table to send the CGI 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 CGI 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 your 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 application 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 significant issue, specify your run-mode methods by reference and not by name.

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.

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 called croak() it will check for the existance of a run-mode called "AUTOLOAD". If specified, this run-mode will in involked just like a regular run-mode, with one exception: It will receive, as an argument, the name of the run-mode which involked it:

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.

In this example, the web user will be forced into the "login" run-mode unless they have aleady 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.

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.

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".

More Reading

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

CGI::Application is developed by The Erlbaum Group, a software engineering and consulting firm in New York City. If you are looking for a company to develop your web site or individual developers to augment your team please contact us:

Thanks to Vanguard Media (http://www.vm.com) for funding the initial development of this library and for encouraging me 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!

The following people have contributed specific suggestions or patches which have helped improve CGI::Application --

Stephen Howard
Mark Stosberg
Steve Comrie

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".)