Rapid Website Development with CGI::Application
by Mark Stosberg
|
Pages: 1, 2, 3, 4
Lazier Than Ever
One frequent feature you'll find in CGI::Application plugins is lazy loading. This means that loading and configuring the plugin often has little resource penalty. Take the DBH plugin. It's convenient to configure the database handle once for a whole website project and then use the handle whenever you want.
Before this plugin arrived, it would be tempting to stuff the database handle into the param method to achieve a similar effect:
sub cgiapp_init {
my $self = shift;
my $dbh = DBI->connect($data_source, $username, $auth, \%attr);
# save for later!
$self->param('dbh',$dbh);
}
That works OK, but it misses a valuable feature: lazy loading.
Lazy loading creates the database connection only if any code needs to use it. This avoids needlessly creating a database connection for scripts that don't need it, while still being very convenient. Here's an example:
# define the database connection parameters once in a super class, for a whole
# suite of child applications:
sub cgiapp_init {
my $self = shift;
# use the same args as DBI->connect();
$self->dbh_config($data_source, $username, $auth, \%attr);
}
Then, whenever you need a database handle:
sub my_run_mode : Runmode {
my $self = shift;
my $result = $self->dbh->selectrow("...");
# ...
}
Easy. dbh_config() will get called on every request, but it simply stores the configuration details. The database handle gets created only during calls to the dbh() method.
Another notable lazy-loading plugin is the Session plugin, which provides easy access to a CGI::Session object. It further takes advantage of the CGI::Application framework by automatically setting the session cookie for you, so you don't have to deal with cookies unless you want to.
Ready for High-Performance Environments
I mostly use CGI::Application with plain CGI, because it performs well enough and works well in a shared hosting environment since no resources persist between requests.
However, CGI::Application is ready for high-performance applications.
Often, code written for CGI::Application will run without changes under mod_perl's Apache::Registry mode, as 1-800-Save-A-Pet.com does.
To squeeze a little more juice out of mod_perl, there is an Apache plugin, which uses Apache::Request instead of CGI.pm.
A current popular alternative for increasing performance is FastCGI. Use CGI::Application::FastCGI, and add, usually, just one line of code to make your application work in this environment.

