perldoc > CGI::Application

📘 NAME

CGI::Application - Framework for building reusable web-applications

🚀 Quick Reference

Use CaseCommandDescription
🔧 Create application moduleuse base 'CGI::Application';Inherit from CGI::Application
⚙️ Define run modes$self->run_modes({ 'mode' => 'sub' });Map run mode names to methods
🚀 Run application$webapp->run();Execute the application
🌐 PSGI modeWebApp->psgi_app();Return PSGI coderef
💾 Database connection$self->dbh_config();Connect via plugin
📄 Load template$self->load_tmpl('file.html');Get HTML::Template object
📝 Set HTTP headers$self->header_props(-type => 'text/html');Modify response headers
🔀 Redirect$self->header_type('redirect'); $self->header_props(-url => '...');Redirect to another URL
❌ Error handling$self->error_mode('my_error_rm');Define error run mode
🔌 Use pluginsuse CGI::Application::Plugin::DBH;Extend functionality

📋 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();

📖 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 PLUG-INS 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.

💡 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'
    );
    $self->dbh_config();
}

sub teardown {
    my $self = shift;
    $self->dbh->disconnect();
}

sub showform {
    my $self = shift;
    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;
    my $dbh = $self->dbh();
    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" ...
    $output .= $q->end_html();
    return $output;
}

sub showdetail {
    my $self = shift;
    my $dbh = $self->dbh();
    my $q = $self->query();
    my $widgetid = $q->param("widgetid");
    my $output = '';
    $output .= $q->start_html(-title => 'Widget Detail');
    ## Do a bunch of things ...
    $output .= $q->end_html();
    return $output;
}

1;

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.

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

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 CGI::Application::Plugin::Apache, which integrates with Apache::Request.

📚 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:

🔹 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:

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:

💠 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 to new. This returns a PSGI-compatible coderef, using CGI:::PSGI as the query object.

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

The structure returned is an arrayref: [ 200, [ 'Content-Type' => 'text/html' ], [ $body ] ].

Example PSGI handler:

use WebApp;
use CGI::PSGI;

my $handler = sub {
    my $env = shift;
    my $webapp = WebApp->new({ QUERY => CGI::PSGI->new($env) });
    $webapp->run_as_psgi;
};

🔹 Additional PSGI Return Values

The PSGI Specification allows for returning a file handle or a subroutine reference instead of byte strings. In PSGI mode this is supported directly by CGI::Application. Have your run mode return a file handle or compatible subref as follows:

sub returning_a_file_handle {
    my $self = shift;
    $self->header_props(-type => 'text/plain');
    open my $fh, "<", 'test_file.txt' or die "OOPS! $!";
    return $fh;
}

sub returning_a_subref {
    my $self = shift;
    $self->header_props(-type => 'text/plain');
    return sub {
       my $writer = shift;
       foreach my $i (1..10) {
           $writer->write("check $i: " . time . "\n");
       }
    };
}

🔹 Methods to possibly override

CGI::Application implements some methods which are expected to be overridden in your sub-class module.

💠 setup()

This method is called by the inherited new() constructor method. The setup() method should be used to define the following property/methods:

Example:

sub setup {
    my $self = shift;
    $self->tmpl_path('/path/to/my/templates/');
    $self->start_mode('putform');
    $self->error_mode('my_error_rm');
    $self->run_modes({
            'putform'  => 'my_putform_func',
            'postdata' => 'my_data_func'
    });
    $self->param('myprop1');
    $self->param('myprop2', 'prop2value');
    $self->param('myprop3', ['p3v1', 'p3v2', 'p3v3']);
}

💠 teardown()

If implemented, this method is called automatically after your application runs. It can be used to clean up after your operations. Typical use: disconnect a database connection.

💠 cgiapp_init()

If implemented, this method is called automatically right before the setup() method is called. This method provides an optional initialization hook. It receives all arguments sent to new().

Example: creating a custom "application super-class":

# In MySuperclass.pm:
package MySuperclass;
use base 'CGI::Application';
sub cgiapp_init {
    my $self = shift;
    # Perform some project-specific init behavior
}

# In MyApplication.pm:
package MyApplication;
use base 'MySuperclass';
sub setup { ... }
sub teardown { ... }

💠 cgiapp_prerun()

If implemented, this method is called automatically right before the selected run mode method is called. It receives the value of the run mode. You can change the run mode using prerun_mode().

Example: authorization check:

sub cgiapp_prerun {
    my $self = shift;
    my $q = $self->query();
    my $user = $q->remote_user();
    unless ($user) {
        $self->prerun_mode('login');
    }
}

💠 cgiapp_postrun()

If implemented, this hook will be called after the run mode method has returned its output, but before HTTP headers are generated. It receives a reference to the output.

Example: enclose output in an HTML table:

sub cgiapp_postrun {
    my $self = shift;
    my $output_ref = shift;
    my $new_output = "<table border=1>";
    $new_output .= "<tr><td> Hello, World! </td></tr>";
    $new_output .= "<tr><td>". $$output_ref ."</td></tr>";
    $new_output .= "</table>";
    $$output_ref = $new_output;
}

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

🔹 Essential Application Methods

The following methods are inherited from CGI::Application and are available to be called by your application within your Application Module.

💠 load_tmpl()

my $tmpl_obj = $webapp->load_tmpl;
my $tmpl_obj = $webapp->load_tmpl('some.html');
my $tmpl_obj = $webapp->load_tmpl( \$template_content );
my $tmpl_obj = $webapp->load_tmpl( FILEHANDLE );

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, it defaults to the current run mode name plus ".html".

You can pass extra parameters to HTML::Template:

my $tmpl_obj = $webapp->load_tmpl('some_other.html',
     die_on_bad_params => 0,
     cache => 1
);

To use default template name with extra arguments:

my $tmpl_obj = $webapp->load_tmpl(undef,
     die_on_bad_params => 0,
     cache => 1
);

Alternatives to load_tmpl(): See template plugins like CGI::Application::Plugin::TT or CGI::Application::Plugin::Stream. You can also specify an alternative template class using html_tmpl_class().

load_tmpl() callback: Plugin authors can register a callback to modify template parameters before load_tmpl() returns.

💠 param()

$webapp->param('pname', $somevalue);
my $scalar_param_values = $webapp->param('some_param');
my @all_params = $webapp->param();

Set or get application instance properties. Can also set multiple params at once:

$webapp->param(
    'key1' => 'val1',
    'key2' => 'val2',
    'key3' => 'val3',
);

💠 query()

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

Retrieves the CGI.pm query object. You can also set a custom query object:

$webapp->query($new_query_object);

💠 run_modes()

# Arrayref of run mode names that exactly match subroutine names
$webapp->run_modes([qw/
    form_display
    form_process
/]);

# Hashref with a different name or a code ref
$webapp->run_modes(
    'mode1' => 'some_sub_by_name',
    'mode2' => \&some_other_sub_by_ref
);

Specifies the dispatch table for the application states. The run() method uses this table to call the correct function. The run mode method is expected to return a block of text (e.g., HTML) as a scalar or scalar-ref.

IMPORTANT NOTE: Your application should NEVER print() to STDOUT. The inherited run() method handles output.

THE RUN MODE OF LAST RESORT: "AUTOLOAD": If a run mode doesn't exist, you can implement an "AUTOLOAD" run mode to catch it:

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

sub catch_my_exception {
    my $self = shift;
    my $intended_runmode = shift;
    my $output = "Looking for '$intended_runmode', but found 'AUTOLOAD' instead";
    return $output;
}

💠 start_mode()

$webapp->start_mode('mode1');

Contains the name of the mode as specified in the run_modes() table. Default is "start". Used when the run mode CGI param is not defined.

💠 tmpl_path()

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

Sets the file path to the directory (or directories) where templates are stored. Used by load_tmpl().

🔹 More Application Methods

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

💠 delete()

$webapp->delete('my_param');

Deletes a parameter previously stored via param() or new().

💠 dump()

print STDERR $webapp->dump();

Debugging function that returns a chunk of text containing all environment and web form data, formatted for human readability. Useful for outputting to STDERR.

💠 dump_html()

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

Same as dump() but formatted for a web browser. Be careful with security in production.

💠 error_mode()

$webapp->error_mode('my_error_rm');

If a run mode dies, run() will call this method as a run mode, passing $@ as the only parameter. No error_mode is defined by default.

💠 get_current_runmode()

$webapp->get_current_runmode();

Returns the name of the run mode currently being executed. Returns undef during setup().

💠 header_add()

# add or replace the 'type' header
$webapp->header_add( -type => 'image/png' );

- or -

# add an additional cookie
$webapp->header_add(-cookie=>[$extra_cookie]);

Adds one or more headers to the outgoing response headers. Preserves existing headers; scalar values replace, array values append.

💠 header_props()

# Set a complete set of headers
$webapp->header_props(-type=>'image/gif',-expires=>'+3d');

# clobber / reset all headers
$webapp->header_props({});

# Just retrieve the headers
my %set_headers = $webapp->header_props();

Sets or gets CGI.pm-compatible HTTP header properties. Works in conjunction with header_type().

💠 header_type()

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

Declares that you are setting a redirection header, or that you want no header to be returned. Example redirect:

sub some_redirect_mode {
    my $self = shift;
    $self->header_type('redirect');
    $self->header_props(-url=> "http://site/path/doc.html" );
}

💠 mode_param()

# Name the CGI form parameter that contains the run mode name.
$webapp->mode_param('rm');

# Set the run mode name directly from a code ref
$webapp->mode_param(\&some_method);

# Alternate interface using $ENV{PATH_INFO}
$webapp->mode_param(
    path_info=> 1,
    param =>'rm'
);

Helps determine the run mode to call. The code ref example:

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

Using path_info: $webapp->mode_param( path_info=> 2 ); gets the run mode from the 2nd part of $ENV{PATH_INFO}. Negative values work like list indices.

💠 prerun_mode()

$webapp->prerun_mode('new_run_mode');

Can be used within cgiapp_prerun() to change the run mode that is about to be executed. May only be called in the context of cgiapp_prerun().

🔹 Dispatching Clean URIs to run modes

Modern web frameworks provide clean URIs instead of cruft. For mapping URIs to run modes, see CGI::Application::Dispatch. Dispatching is not required and can be added later.

🔹 Offline website development

You can work on your CGI::Application project on your desktop without a full-featured web server. Install CGI::Application::Server from CPAN.

🔹 Automated Testing

Test::WWW::Mechanize::CGIApp allows functional testing without starting a web server. Direct testing is also easy:

$ENV{CGI_APP_RETURN_ONLY} = 1;
$output = $webapp->run();
like($output, qr/good/, "output is good");

🔌 PLUG-INS

CGI::Application has a plug-in architecture that is easy to use and easy to develop new plug-ins for.

🔹 Recommended Plug-ins

🔹 More plug-ins

For a current complete list, consult CPAN: http://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin

🔹 Writing Plug-ins

Simply create a new package and export the methods. See CGI::Application::Plugin::ValidateRM for an example. To avoid namespace conflicts, use a unique prefix:

$app->{'MyPlugin::Module::__PARAM'} = 'foo'; # Good.
$app->{'MyPlugin::Module'}{__PARAM} = 'foo'; # Good.

🔹 Writing Advanced Plug-ins - Using callbacks

When writing a plug-in, you may want some action to happen automatically at a particular stage. Use callback methods:

Callback Examples:

# 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);

# Create a new hook
$self->new_hook('pretemplate');

# Then later execute all the callbacks registered at this hook
$self->call_hook('pretemplate');

Callback Ordering: Object-based callbacks run before class-based. The order of class-based callbacks is determined by the inheritance tree.

👥 COMMUNITY

🔗 SEE ALSO

📖 MORE READING

👤 AUTHOR

Jesse Erlbaum <jesse AT erlbaum.net>

Mark Stosberg has served as a co-maintainer since version 3.2, Martin McGrath became a co-maintainer as of version 4.51.

🙏 CREDITS

CGI::Application was originally developed by The Erlbaum Group. Thanks to Vanguard Media (http://www.vm.com) for funding the initial development. Many thanks to Sam Tregar for his contributions. Thanks to all members of the CGI-App mailing list.

📜 LICENSE

CGI::Application : Framework for building reusable web-applications Copyright (C) 2000-2003 Jesse Erlbaum <jesse AT erlbaum.net>

This module is free software; you can redistribute it and/or modify it under the terms of either the GNU General Public License (version 1 or later) or the "Artistic License".

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the GNU General Public License or the Artistic License for more details.

CGI::Application
📘 NAME 🚀 Quick Reference 📋 SYNOPSIS 📖 INTRODUCTION 💡 USAGE EXAMPLE 📝 ABSTRACT 📚 DESCRIPTION
🔹 Instance Script Methods 🔹 Additional PSGI Return Values 🔹 Methods to possibly override 🔹 Essential Application Methods 🔹 More Application Methods 🔹 Dispatching Clean URIs to run modes 🔹 Offline website development 🔹 Automated Testing
🔌 PLUG-INS
🔹 Recommended Plug-ins 🔹 More plug-ins 🔹 Writing Plug-ins 🔹 Writing Advanced Plug-ins - Using callbacks
👥 COMMUNITY 🔗 SEE ALSO 📖 MORE READING 👤 AUTHOR 🙏 CREDITS 📜 LICENSE

Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-06 04:57 @216.73.216.192
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Valid XHTML 1.0 Transitional!Valid CSS!
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format

^_top_^