package CGI::Application;
use Carp;
use strict;
use Class::ISA;
use Scalar::Util;
$CGI::Application::VERSION = '4.61';
my %INSTALLED_CALLBACKS = (
# hook name package sub
init => { 'CGI::Application' => [ 'cgiapp_init' ] },
prerun => { 'CGI::Application' => [ 'cgiapp_prerun' ] },
postrun => { 'CGI::Application' => [ 'cgiapp_postrun' ] },
teardown => { 'CGI::Application' => [ 'teardown' ] },
load_tmpl => { },
error => { },
);
###################################
#### INSTANCE SCRIPT METHODS ####
###################################
sub new {
my $class = shift;
my @args = @_;
if (ref($class)) {
# No copy constructor yet!
$class = ref($class);
}
# Create our object!
my $self = {};
bless($self, $class);
### SET UP DEFAULT VALUES ###
#
# We set them up here and not in the setup() because a subclass
# which implements setup() still needs default values!
$self->header_type('header');
$self->mode_param('rm');
$self->start_mode('start');
# Process optional new() parameters
my $rprops;
if (ref($args[0]) eq 'HASH') {
$rprops = $self->_cap_hash($args[0]);
} else {
$rprops = $self->_cap_hash({ @args });
}
# Set tmpl_path()
if (exists($rprops->{TMPL_PATH})) {
$self->tmpl_path($rprops->{TMPL_PATH});
}
# Set CGI query object
if (exists($rprops->{QUERY})) {
$self->query($rprops->{QUERY});
}
# Set up init param() values
if (exists($rprops->{PARAMS})) {
croak("PARAMS is not a hash ref") unless (ref($rprops->{PARAMS}) eq 'HASH');
my $rparams = $rprops->{PARAMS};
while (my ($k, $v) = each(%$rparams)) {
$self->param($k, $v);
}
}
# Lock prerun_mode from being changed until cgiapp_prerun()
$self->{__PRERUN_MODE_LOCKED} = 1;
# Call cgiapp_init() method, which may be implemented in the sub-class.
# Pass all constructor args forward. This will allow flexible usage
# down the line.
$self->call_hook('init', @args);
# Call setup() method, which should be implemented in the sub-class!
$self->setup();
return $self;
}
sub __get_runmode {
my $self = shift;
my $rm_param = shift;
my $rm;
# Support call-back instead of CGI mode param
if (ref($rm_param) eq 'CODE') {
# Get run mode from subref
$rm = $rm_param->($self);
}
# support setting run mode from PATH_INFO
elsif (ref($rm_param) eq 'HASH') {
$rm = $rm_param->{run_mode};
}
# Get run mode from CGI param
else {
$rm = $self->query->param($rm_param);
}
# If $rm undefined, use default (start) mode
$rm = $self->start_mode unless defined($rm) && length($rm);
return $rm;
}
sub __get_runmeth {
my $self = shift;
my $rm = shift;
my $rmeth;
my $is_autoload = 0;
my %rmodes = ($self->run_modes());
if (exists($rmodes{$rm})) {
$rmeth = $rmodes{$rm};
}
else {
# Look for run mode "AUTOLOAD" before dieing
unless (exists($rmodes{'AUTOLOAD'})) {
croak("No such run mode '$rm'");
}
$rmeth = $rmodes{'AUTOLOAD'};
$is_autoload = 1;
}
return ($rmeth, $is_autoload);
}
sub __get_body {
my $self = shift;
my $rm = shift;
my ($rmeth, $is_autoload) = $self->__get_runmeth($rm);
my $body;
eval {
$body = $is_autoload ? $self->$rmeth($rm) : $self->$rmeth();
};
if ($@) {
my $error = $@;
$self->call_hook('error', $error);
if (my $em = $self->error_mode) {
$body = $self->$em( $error );
} else {
croak("Error executing run mode '$rm': $error");
}
}
# Make sure that $body is not undefined (suppress 'uninitialized value'
# warnings)
return defined $body ? $body : '';
}
sub run {
my $self = shift;
my $q = $self->query();
my $rm_param = $self->mode_param();
my $rm = $self->__get_runmode($rm_param);
# Set get_current_runmode() for access by user later
$self->{__CURRENT_RUNMODE} = $rm;
# Allow prerun_mode to be changed
delete($self->{__PRERUN_MODE_LOCKED});
# Call PRE-RUN hook, now that we know the run mode
# This hook can be used to provide run mode specific behaviors
# before the run mode actually runs.
$self->call_hook('prerun', $rm);
# Lock prerun_mode from being changed after cgiapp_prerun()
$self->{__PRERUN_MODE_LOCKED} = 1;
# If prerun_mode has been set, use it!
my $prerun_mode = $self->prerun_mode();
if (length($prerun_mode)) {
$rm = $prerun_mode;
$self->{__CURRENT_RUNMODE} = $rm;
}
# Process run mode!
my $body = $self->__get_body($rm);
# Support scalar-ref for body return
$body = $$body if ref $body eq 'SCALAR';
# Call cgiapp_postrun() hook
$self->call_hook('postrun', \$body);
my $return_value;
if ($self->{__IS_PSGI}) {
my ($status, $headers) = $self->_send_psgi_headers();
if (ref($body) eq 'GLOB' || (Scalar::Util::blessed($body) && $body->can('getline'))) {
# body a file handle - return it
$return_value = [ $status, $headers, $body];
}
elsif (ref($body) eq 'CODE') {
# body is a subref, or an explicit callback method is set
$return_value = sub {
my $respond = shift;
my $writer = $respond->([ $status, $headers ]);
&$body($writer);
};
}
else {
$return_value = [ $status, $headers, [ $body ]];
}
}
else {
# Set up HTTP headers non-PSGI responses
my $headers = $self->_send_headers();
# Build up total output
$return_value = $headers.$body;
print $return_value unless $ENV{CGI_APP_RETURN_ONLY};
}
# clean up operations
$self->call_hook('teardown');
return $return_value;
}
sub psgi_app {
my $class = shift;
my $args_to_new = shift;
return sub {
my $env = shift;
# PR from alter https://github.com/markstos/CGI--Application/pull/17
#if (not defined $args_to_new->{QUERY}) {
require CGI::PSGI;
$args_to_new->{QUERY} = CGI::PSGI->new($env);
#}
my $webapp = $class->new($args_to_new);
return $webapp->run_as_psgi;
}
}
sub run_as_psgi {
my $self = shift;
$self->{__IS_PSGI} = 1;
# Run doesn't officially support any args, but pass them through in case some sub-class uses them.
return $self->run(@_);
}
############################
#### OVERRIDE METHODS ####
############################
sub cgiapp_get_query {
my $self = shift;
# Include CGI.pm and related modules
require CGI;
# Get the query object
my $q = CGI->new();
return $q;
}
sub cgiapp_init {
my $self = shift;
my @args = (@_);
# Nothing to init, yet!
}
sub cgiapp_prerun {
my $self = shift;
my $rm = shift;
# Nothing to prerun, yet!
}
sub cgiapp_postrun {
my $self = shift;
my $bodyref = shift;
# Nothing to postrun, yet!
}
sub setup {
my $self = shift;
}
sub teardown {
my $self = shift;
# Nothing to shut down, yet!
}
######################################
#### APPLICATION MODULE METHODS ####
######################################
sub dump {
my $self = shift;
my $output = '';
# Dump run mode
my $current_runmode = $self->get_current_runmode();
$current_runmode = "" unless (defined($current_runmode));
$output .= "Current Run mode: '$current_runmode'\n";
# Dump Params
# updated ->param to ->multi_param to silence CGI.pm warning
$output .= "\nQuery Parameters:\n";
my @params = $self->query->multi_param();
foreach my $p (sort(@params)) {
my @data = $self->query->multi_param($p);
my $data_str = "'".join("', '", @data)."'";
$output .= "\t$p => $data_str\n";
}
# Dump ENV
$output .= "\nQuery Environment:\n";
foreach my $ek (sort(keys(%ENV))) {
$output .= "\t$ek => '".$ENV{$ek}."'\n";
}
return $output;
}
sub dump_html {
my $self = shift;
my $query = $self->query();
my $output = '';
# Dump run-mode
my $current_runmode = $self->get_current_runmode();
$output .= "
Current Run-mode:
'$current_runmode'
\n";
# Dump Params
$output .= "Query Parameters:
\n";
$output .= $query->Dump;
# Dump ENV
$output .= "Query Environment:
\n\n";
foreach my $ek ( sort( keys( %ENV ) ) ) {
$output .= sprintf(
"- %s => '%s'
\n",
$query->escapeHTML( $ek ),
$query->escapeHTML( $ENV{$ek} )
);
}
$output .= "
\n";
return $output;
}
sub no_runmodes {
my $self = shift;
my $query = $self->query();
my $output = $query->start_html;
# If no runmodes specified by app return error message
my $current_runmode = $self->get_current_runmode();
my $query_params = $query->Dump;
$output .= qq{
Error - No runmodes specified.
Runmode called: $current_runmode"
Query paramaters:
$query_params
Your application has not specified any runmodes.
Please read the
CGI::Application documentation.
};
$output .= $query->end_html();
return $output;
}
sub header_add {
my $self = shift;
return $self->_header_props_update(\@_,add=>1);
}
sub header_props {
my $self = shift;
return $self->_header_props_update(\@_,add=>0);
}
# used by header_props and header_add to update the headers
sub _header_props_update {
my $self = shift;
my $data_ref = shift;
my %in = @_;
my @data = @$data_ref;
# First use? Create new __HEADER_PROPS!
$self->{__HEADER_PROPS} = {} unless (exists($self->{__HEADER_PROPS}));
my $props;
# If data is provided, set it!
if (scalar(@data)) {
if ($self->header_type eq 'none') {
warn "header_props called while header_type set to 'none', headers will NOT be sent!"
}
# Is it a hash, or hash-ref?
if (ref($data[0]) eq 'HASH') {
# Make a copy
%$props = %{$data[0]};
} elsif ((scalar(@data) % 2) == 0) {
# It appears to be a possible hash (even # of elements)
%$props = @data;
} else {
my $meth = $in{add} ? 'add' : 'props';
croak("Odd number of elements passed to header_$meth(). Not a valid hash")
}
# merge in new headers, appending new values passed as array refs
if ($in{add}) {
for my $key_set_to_aref (grep { ref $props->{$_} eq 'ARRAY'} keys %$props) {
my $existing_val = $self->{__HEADER_PROPS}->{$key_set_to_aref};
next unless defined $existing_val;
my @existing_val_array = (ref $existing_val eq 'ARRAY') ? @$existing_val : ($existing_val);
$props->{$key_set_to_aref} = [ @existing_val_array, @{ $props->{$key_set_to_aref} } ];
}
$self->{__HEADER_PROPS} = { %{ $self->{__HEADER_PROPS} }, %$props };
}
# Set new headers, clobbering existing values
else {
$self->{__HEADER_PROPS} = $props;
}
}
# If we've gotten this far, return the value!
return (%{ $self->{__HEADER_PROPS}});
}
sub header_type {
my $self = shift;
my ($header_type) = @_;
my @allowed_header_types = qw(header redirect none);
# First use? Create new __HEADER_TYPE!
$self->{__HEADER_TYPE} = 'header' unless (exists($self->{__HEADER_TYPE}));
# If data is provided, set it!
if (defined($header_type)) {
$header_type = lc($header_type);
croak("Invalid header_type '$header_type'")
unless(grep { $_ eq $header_type } @allowed_header_types);
$self->{__HEADER_TYPE} = $header_type;
}
# If we've gotten this far, return the value!
return $self->{__HEADER_TYPE};
}
sub param {
my $self = shift;
my (@data) = (@_);
# First use? Create new __PARAMS!
$self->{__PARAMS} = {} unless (exists($self->{__PARAMS}));
my $rp = $self->{__PARAMS};
# If data is provided, set it!
if (scalar(@data)) {
# Is it a hash, or hash-ref?
if (ref($data[0]) eq 'HASH') {
# Make a copy, which augments the existing contents (if any)
%$rp = (%$rp, %{$data[0]});
} elsif ((scalar(@data) % 2) == 0) {
# It appears to be a possible hash (even # of elements)
%$rp = (%$rp, @data);
} elsif (scalar(@data) > 1) {
croak("Odd number of elements passed to param(). Not a valid hash");
}
} else {
# Return the list of param keys if no param is specified.
return (keys(%$rp));
}
# If exactly one parameter was sent to param(), return the value
if (scalar(@data) <= 2) {
my $param = $data[0];
return $rp->{$param};
}
return; # Otherwise, return undef
}
sub delete {
my $self = shift;
my ($param) = @_;
# return undef it the param name isn't given
return undef unless defined $param;
#simply delete this param from $self->{__PARAMS}
delete $self->{__PARAMS}->{$param};
}
sub query {
my $self = shift;
my ($query) = @_;
# If data is provided, set it! Otherwise, create a new one.
if (defined($query)) {
$self->{__QUERY_OBJ} = $query;
} else {
# We're only allowed to create a new query object if one does not yet exist!
unless (exists($self->{__QUERY_OBJ})) {
$self->{__QUERY_OBJ} = $self->cgiapp_get_query();
}
}
return $self->{__QUERY_OBJ};
}
sub run_modes {
my $self = shift;
my (@data) = (@_);
# First use? Create new __RUN_MODES!
$self->{__RUN_MODES} = { 'start' => 'no_runmodes' } unless (exists($self->{__RUN_MODES}));
my $rr_m = $self->{__RUN_MODES};
# If data is provided, set it!
if (scalar(@data)) {
# Is it a hash, hash-ref, or array-ref?
if (ref($data[0]) eq 'HASH') {
# Make a copy, which augments the existing contents (if any)
%$rr_m = (%$rr_m, %{$data[0]});
} elsif (ref($data[0]) eq 'ARRAY') {
# Convert array-ref into hash table
foreach my $rm (@{$data[0]}) {
$rr_m->{$rm} = $rm;
}
} elsif ((scalar(@data) % 2) == 0) {
# It appears to be a possible hash (even # of elements)
%$rr_m = (%$rr_m, @data);
} else {
croak("Odd number of elements passed to run_modes(). Not a valid hash");
}
}
# If we've gotten this far, return the value!
return (%$rr_m);
}
sub start_mode {
my $self = shift;
my ($start_mode) = @_;
# First use? Create new __START_MODE
$self->{__START_MODE} = 'start' unless (exists($self->{__START_MODE}));
# If data is provided, set it
if (defined($start_mode)) {
$self->{__START_MODE} = $start_mode;
}
return $self->{__START_MODE};
}
sub error_mode {
my $self = shift;
my ($error_mode) = @_;
# First use? Create new __ERROR_MODE
$self->{__ERROR_MODE} = undef unless (exists($self->{__ERROR_MODE}));
# If data is provided, set it.
if (defined($error_mode)) {
$self->{__ERROR_MODE} = $error_mode;
}
return $self->{__ERROR_MODE};
}
sub tmpl_path {
my $self = shift;
my ($tmpl_path) = @_;
# First use? Create new __TMPL_PATH!
$self->{__TMPL_PATH} = '' unless (exists($self->{__TMPL_PATH}));
# If data is provided, set it!
if (defined($tmpl_path)) {
$self->{__TMPL_PATH} = $tmpl_path;
}
# If we've gotten this far, return the value!
return $self->{__TMPL_PATH};
}
sub prerun_mode {
my $self = shift;
my ($prerun_mode) = @_;
# First use? Create new __PRERUN_MODE
$self->{__PRERUN_MODE} = '' unless (exists($self->{__PRERUN_MODE}));
# Was data provided?
if (defined($prerun_mode)) {
# Are we allowed to set prerun_mode?
if (exists($self->{__PRERUN_MODE_LOCKED})) {
# Not allowed! Throw an exception.
croak("prerun_mode() can only be called within cgiapp_prerun()! Error");
} else {
# If data is provided, set it!
$self->{__PRERUN_MODE} = $prerun_mode;
}
}
# If we've gotten this far, return the value!
return $self->{__PRERUN_MODE};
}
sub get_current_runmode {
my $self = shift;
# It's OK if we return undef if this method is called too early
return $self->{__CURRENT_RUNMODE};
}
###########################
#### PRIVATE METHODS ####
###########################
# return headers as a string
sub _send_headers {
my $self = shift;
my $q = $self->query;
my $type = $self->header_type;
return
$type eq 'redirect' ? $q->redirect( $self->header_props )
: $type eq 'header' ? $q->header ( $self->header_props )
: $type eq 'none' ? ''
: croak "Invalid header_type '$type'"
}
# return a 2 element array modeling the first PSGI redirect values: status code and arrayref of header pairs
sub _send_psgi_headers {
my $self = shift;
my $q = $self->query;
my $type = $self->header_type;
return
$type eq 'redirect' ? $q->psgi_redirect( $self->header_props )
: $type eq 'header' ? $q->psgi_header ( $self->header_props )
: $type eq 'none' ? ''
: croak "Invalid header_type '$type'"
}
# Make all hash keys CAPITAL
# although this method is internal, some other extensions
# have come to rely on it, so any changes here should be
# made with great care or avoided.
sub _cap_hash {
my $self = shift;
my $rhash = shift;
my %hash = map {
my $k = $_;
my $v = $rhash->{$k};
$k =~ tr/a-z/A-Z/;
$k => $v;
} keys(%{$rhash});
return \%hash;
}
1;
=pod
=head1 NAME
CGI::Application - Framework for building reusable web-applications
=head1 SYNOPSIS
# In "WebApp.pm"...
package WebApp;
use base 'CGI::Application';
# ( setup() can even be skipped for common cases. See docs below. )
sub setup {
my $self = shift;
$self->start_mode('mode1');
$self->mode_param('rm');
$self->run_modes(
'mode1' => 'do_stuff',
'mode2' => 'do_more_stuff',
'mode3' => 'do_something_else'
);
}
sub do_stuff { ... }
sub do_more_stuff { ... }
sub do_something_else { ... }
1;
### In "webapp.cgi"...
use WebApp;
my $webapp = WebApp->new();
$webapp->run();
### Or, in a PSGI file, webapp.psgi
use WebApp;
WebApp->psgi_app();
=head1 INTRODUCTION
CGI::Application makes it easier to create sophisticated, high-performance,
reusable web-based applications. CGI::Application helps makes your web
applications easier to design, write, and evolve.
CGI::Application judiciously avoids employing technologies and techniques which
would bind a developer to any one set of tools, operating system or web server.
It is lightweight in terms of memory usage, making it suitable for common CGI
environments, and a high performance choice in persistent environments like
FastCGI or mod_perl.
By adding L as your needs grow, you can add advanced and complex
features when you need them.
First released in 2000 and used and expanded by a number of professional
website developers, CGI::Application is a stable, reliable choice.
=head1 USAGE EXAMPLE
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:
1. WidgetView.pm -- Your "Application Module"
2. widgetview.cgi -- Your "Instance Script"
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":
#!/usr/bin/perl -w
use WidgetView;
my $webapp = WidgetView->new();
$webapp->run();
As you can see, widgetview.cgi simply "uses" your Application module
(which implements a Perl package called "WidgetView"). Your Application Module,
"WidgetView.pm", is somewhat more lengthy:
package WidgetView;
use base 'CGI::Application';
use strict;
# Needed for our database connection
use CGI::Application::Plugin::DBH;
sub setup {
my $self = shift;
$self->start_mode('mode1');
$self->run_modes(
'mode1' => 'showform',
'mode2' => 'showlist',
'mode3' => 'showdetail'
);
# Connect to DBI database, with the same args as DBI->connect();
$self->dbh_config();
}
sub teardown {
my $self = shift;
# Disconnect when we're done, (Although DBI usually does this automatically)
$self->dbh->disconnect();
}
sub showform {
my $self = shift;
# Get CGI query object
my $q = $self->query();
my $output = '';
$output .= $q->start_html(-title => 'Widget Search Form');
$output .= $q->start_form();
$output .= $q->textfield(-name => 'widgetcode');
$output .= $q->hidden(-name => 'rm', -value => 'mode2');
$output .= $q->submit();
$output .= $q->end_form();
$output .= $q->end_html();
return $output;
}
sub showlist {
my $self = shift;
# Get our database connection
my $dbh = $self->dbh();
# Get CGI query object
my $q = $self->query();
my $widgetcode = $q->param("widgetcode");
my $output = '';
$output .= $q->start_html(-title => 'List of Matching Widgets');
## Do a bunch of stuff to select "widgets" from a DBI-connected
## database which match the user-supplied value of "widgetcode"
## which has been supplied from the previous HTML form via a
## CGI.pm query object.
##
## Each row will contain a link to a "Widget Detail" which
## provides an anchor tag, as follows:
##
## "widgetview.cgi?rm=mode3&widgetid=XXX"
##
## ...Where "XXX" is a unique value referencing the ID of
## the particular "widget" upon which the user has clicked.
$output .= $q->end_html();
return $output;
}
sub showdetail {
my $self = shift;
# Get our database connection
my $dbh = $self->dbh();
# Get CGI query object
my $q = $self->query();
my $widgetid = $q->param("widgetid");
my $output = '';
$output .= $q->start_html(-title => 'Widget Detail');
## Do a bunch of things to select all the properties of
## the particular "widget" upon which the user has
## clicked. The key id value of this widget is provided
## via the "widgetid" property, accessed via the CGI.pm
## query object.
$output .= $q->end_html();
return $output;
}
1; # Perl requires this at the end of all modules
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.
=head1 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.
For more information on using CGI::Application with mod_perl, please see our
website at http://www.cgi-app.org/, as well as
L, which integrates with L.
=head1 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';
B
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)
=head2 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.
=head3 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:
my $webapp = WebApp->new(
TMPL_PATH => 'App/',
PARAMS => {
'custom_thing_1' => 'some val',
'another_custom_thing' => [qw/123 456/]
}
);
This method may take some specific parameters:
B - 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.
B - 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.
B - 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
L, which uses L to support
many configuration file formats.
my $app = WebApp->new(PARAMS => { cfg_file => 'config.pl' });
# Later in your app:
my %cfg = $self->cfg()
# or ... $self->cfg('HTML_ROOT_DIR');
See the list of plugins below for more config file integration solutions.
=head3 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().
=head2 PSGI support
CGI::Application offers native L support. The default query object
for this is L, which simply wrappers CGI.pm to provide PSGI
support to it.
=head3 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 L as the query object. To use a different query
object, construct your own object using C<< 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.
=head3 run_as_psgi()
my $psgi_aref = $webapp->run_as_psgi;
Just like C<< run >>, but prints no output and returns the data structure
required by the L specification. Use this if you want to run the
application on top of a PSGI-compatible handler, such as L provides.
If you are just getting started, just use C<< run() >>. It's easy to switch to using
C<< run_as_psgi >> later.
Why use C<< 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 L 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 L for details about the
response format.
Note that calling C<< run_as_psgi >> only handles the I