1CGI::Application(3)   User Contributed Perl Documentation  CGI::Application(3)
2
3
4

NAME

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

SYNOPSIS

9         # In "WebApp.pm"...
10         package WebApp;
11         use base 'CGI::Application';
12
13         # ( setup() can even be skipped for common cases. See docs below. )
14         sub setup {
15               my $self = shift;
16               $self->start_mode('mode1');
17               $self->mode_param('rm');
18               $self->run_modes(
19                       'mode1' => 'do_stuff',
20                       'mode2' => 'do_more_stuff',
21                       'mode3' => 'do_something_else'
22               );
23         }
24         sub do_stuff { ... }
25         sub do_more_stuff { ... }
26         sub do_something_else { ... }
27         1;
28
29
30         ### In "webapp.cgi"...
31         use WebApp;
32         my $webapp = WebApp->new();
33         $webapp->run();
34
35         ### Or, in a PSGI file, webapp.psgi
36         use WebApp;
37         WebApp->psgi_app();
38

INTRODUCTION

40       CGI::Application makes it easier to create sophisticated, high-
41       performance, reusable web-based applications.  CGI::Application helps
42       makes your web applications easier to design, write, and evolve.
43
44       CGI::Application judiciously avoids employing technologies and
45       techniques which would bind a developer to any one set of tools,
46       operating system or web server.
47
48       It is lightweight in terms of memory usage, making it suitable for
49       common CGI environments, and a high performance choice in persistent
50       environments like FastCGI or mod_perl.
51
52       By adding PLUG-INS as your needs grow, you can add advanced and complex
53       features when you need them.
54
55       First released in 2000 and used and expanded by a number of
56       professional website developers, CGI::Application is a stable, reliable
57       choice.
58

USAGE EXAMPLE

60       Imagine you have to write an application to search through a database
61       of widgets.  Your application has three screens:
62
63          1. Search form
64          2. List of results
65          3. Detail of a single record
66
67       To write this application using CGI::Application you will create two
68       files:
69
70          1. WidgetView.pm -- Your "Application Module"
71          2. widgetview.cgi -- Your "Instance Script"
72
73       The Application Module contains all the code specific to your
74       application functionality, and it exists outside of your web server's
75       document root, somewhere in the Perl library search path.
76
77       The Instance Script is what is actually called by your web server.  It
78       is a very small, simple file which simply creates an instance of your
79       application and calls an inherited method, run().  Following is the
80       entirety of "widgetview.cgi":
81
82          #!/usr/bin/perl -w
83          use WidgetView;
84          my $webapp = WidgetView->new();
85          $webapp->run();
86
87       As you can see, widgetview.cgi simply "uses" your Application module
88       (which implements a Perl package called "WidgetView").  Your
89       Application Module, "WidgetView.pm", is somewhat more lengthy:
90
91          package WidgetView;
92          use base 'CGI::Application';
93          use strict;
94
95          # Needed for our database connection
96          use CGI::Application::Plugin::DBH;
97
98          sub setup {
99               my $self = shift;
100               $self->start_mode('mode1');
101               $self->run_modes(
102                       'mode1' => 'showform',
103                       'mode2' => 'showlist',
104                       'mode3' => 'showdetail'
105               );
106
107               # Connect to DBI database, with the same args as DBI->connect();
108            $self->dbh_config();
109          }
110
111          sub teardown {
112               my $self = shift;
113
114               # Disconnect when we're done, (Although DBI usually does this automatically)
115               $self->dbh->disconnect();
116          }
117
118          sub showform {
119               my $self = shift;
120
121               # Get CGI query object
122               my $q = $self->query();
123
124               my $output = '';
125               $output .= $q->start_html(-title => 'Widget Search Form');
126               $output .= $q->start_form();
127               $output .= $q->textfield(-name => 'widgetcode');
128               $output .= $q->hidden(-name => 'rm', -value => 'mode2');
129               $output .= $q->submit();
130               $output .= $q->end_form();
131               $output .= $q->end_html();
132
133               return $output;
134          }
135
136          sub showlist {
137               my $self = shift;
138
139               # Get our database connection
140               my $dbh = $self->dbh();
141
142               # Get CGI query object
143               my $q = $self->query();
144               my $widgetcode = $q->param("widgetcode");
145
146               my $output = '';
147               $output .= $q->start_html(-title => 'List of Matching Widgets');
148
149               ## Do a bunch of stuff to select "widgets" from a DBI-connected
150               ## database which match the user-supplied value of "widgetcode"
151               ## which has been supplied from the previous HTML form via a
152               ## CGI.pm query object.
153               ##
154               ## Each row will contain a link to a "Widget Detail" which
155               ## provides an anchor tag, as follows:
156               ##
157               ##   "widgetview.cgi?rm=mode3&widgetid=XXX"
158               ##
159               ##  ...Where "XXX" is a unique value referencing the ID of
160               ## the particular "widget" upon which the user has clicked.
161
162               $output .= $q->end_html();
163
164               return $output;
165          }
166
167          sub showdetail {
168               my $self = shift;
169
170               # Get our database connection
171               my $dbh = $self->dbh();
172
173               # Get CGI query object
174               my $q = $self->query();
175               my $widgetid = $q->param("widgetid");
176
177               my $output = '';
178               $output .= $q->start_html(-title => 'Widget Detail');
179
180               ## Do a bunch of things to select all the properties of
181               ## the particular "widget" upon which the user has
182               ## clicked.  The key id value of this widget is provided
183               ## via the "widgetid" property, accessed via the CGI.pm
184               ## query object.
185
186               $output .= $q->end_html();
187
188               return $output;
189          }
190
191          1;  # Perl requires this at the end of all modules
192
193       CGI::Application takes care of implementing the new() and the run()
194       methods.  Notice that at no point do you call print() to send any
195       output to STDOUT.  Instead, all output is returned as a scalar.
196
197       CGI::Application's most significant contribution is in managing the
198       application state.  Notice that all which is needed to push the
199       application forward is to set the value of a HTML form parameter 'rm'
200       to the value of the "run mode" you wish to handle the form submission.
201       This is the key to CGI::Application.
202

ABSTRACT

204       The guiding philosophy behind CGI::Application is that a web-based
205       application can be organized into a specific set of "Run Modes."  Each
206       Run Mode is roughly analogous to a single screen (a form, some output,
207       etc.).  All the Run Modes are managed by a single "Application Module"
208       which is a Perl module.  In your web server's document space there is
209       an "Instance Script" which is called by the web server as a CGI (or an
210       Apache::Registry script if you're using Apache + mod_perl).
211
212       This methodology is an inversion of the "Embedded" philosophy (ASP,
213       JSP, EmbPerl, Mason, etc.) in which there are "pages" for each state of
214       the application, and the page drives functionality.  In
215       CGI::Application, form follows function -- the Application Module
216       drives pages, and the code for a single application is in one place;
217       not spread out over multiple "pages".  If you feel that Embedded
218       architectures are confusing, unorganized, difficult to design and
219       difficult to manage, CGI::Application is the methodology for you!
220
221       Apache is NOT a requirement for CGI::Application.  Web applications
222       based on CGI::Application will run equally well on NT/IIS or any other
223       CGI-compatible environment.  CGI::Application-based projects are,
224       however, ripe for use on Apache/mod_perl servers, as they naturally
225       encourage Good Programming Practices and will often work in persistent
226       environments without modification.
227
228       For more information on using CGI::Application with mod_perl, please
229       see our website at http://www.cgi-app.org/, as well as
230       CGI::Application::Plugin::Apache, which integrates with
231       Apache::Request.
232

DESCRIPTION

234       It is intended that your Application Module will be implemented as a
235       sub-class of CGI::Application. This is done simply as follows:
236
237           package My::App;
238           use base 'CGI::Application';
239
240       Notation and Conventions
241
242       For the purpose of this document, we will refer to the following
243       conventions:
244
245         WebApp.pm   The Perl module which implements your Application Module class.
246         WebApp      Your Application Module class; a sub-class of CGI::Application.
247         webapp.cgi  The Instance Script which implements your Application Module.
248         $webapp     An instance (object) of your Application Module class.
249         $c          Same as $webapp, used in instance methods to pass around the
250                     current object. (Sometimes referred as "$self" in other code)
251
252   Instance Script Methods
253       By inheriting from CGI::Application you have access to a number of
254       built-in methods.  The following are those which are expected to be
255       called from your Instance Script.
256
257       new()
258
259       The new() method is the constructor for a CGI::Application.  It returns
260       a blessed reference to your Application Module package (class).
261       Optionally, new() may take a set of parameters as key => value pairs:
262
263           my $webapp = WebApp->new(
264                       TMPL_PATH => 'App/',
265                       PARAMS => {
266                               'custom_thing_1' => 'some val',
267                               'another_custom_thing' => [qw/123 456/]
268                       }
269           );
270
271       This method may take some specific parameters:
272
273       TMPL_PATH - This optional parameter defines a path to a directory of
274       templates.  This is used by the load_tmpl() method (specified below),
275       and may also be used for the same purpose by other template plugins.
276       This run-time parameter allows you to further encapsulate instantiating
277       templates, providing potential for more re-usability.  It can be either
278       a scalar or an array reference of multiple paths.
279
280       QUERY - This optional parameter allows you to specify an already-
281       created CGI.pm query object.  Under normal use, CGI::Application will
282       instantiate its own CGI.pm query object.  Under certain conditions, it
283       might be useful to be able to use one which has already been created.
284
285       PARAMS - This parameter, if used, allows you to set a number of custom
286       parameters at run-time.  By passing in different values in different
287       instance scripts which use the same application module you can achieve
288       a higher level of re-usability.  For instance, imagine an application
289       module, "Mailform.pm".  The application takes the contents of a HTML
290       form and emails it to a specified recipient.  You could have multiple
291       instance scripts throughout your site which all use this "Mailform.pm"
292       module, but which set different recipients or different forms.
293
294       One common use of instance scripts is to provide a path to a config
295       file.  This design allows you to define project wide configuration
296       objects used by many several instance scripts. There are several
297       plugins which simplify the syntax for this and provide lazy loading.
298       Here's an example using CGI::Application::Plugin::ConfigAuto, which
299       uses Config::Auto to support many configuration file formats.
300
301        my $app = WebApp->new(PARAMS => { cfg_file => 'config.pl' });
302
303        # Later in your app:
304        my %cfg = $self->cfg()
305        # or ... $self->cfg('HTML_ROOT_DIR');
306
307       See the list of plugins below for more config file integration
308       solutions.
309
310       run()
311
312       The run() method is called upon your Application Module object, from
313       your Instance Script.  When called, it executes the functionality in
314       your Application Module.
315
316           my $webapp = WebApp->new();
317           $webapp->run();
318
319       This method first determines the application state by looking at the
320       value of the CGI parameter specified by mode_param() (defaults to 'rm'
321       for "Run Mode"), which is expected to contain the name of the mode of
322       operation.  If not specified, the state defaults to the value of
323       start_mode().
324
325       Once the mode has been determined, run() looks at the dispatch table
326       stored in run_modes() and finds the function pointer which is keyed
327       from the mode name.  If found, the function is called and the data
328       returned is print()'ed to STDOUT and to the browser.  If the specified
329       mode is not found in the run_modes() table, run() will croak().
330
331   PSGI support
332       CGI::Application offers native PSGI support. The default query object
333       for this is CGI::PSGI, which simply wrappers CGI.pm to provide PSGI
334       support to it.
335
336       psgi_app()
337
338        $psgi_coderef = WebApp->psgi_app({ ... args to new() ... });
339
340       The simplest way to create and return a PSGI-compatible coderef. Pass
341       in arguments to a hashref just as would to new. This returns a PSGI-
342       compatible coderef, using CGI:::PSGI as the query object. To use a
343       different query object, construct your own object using
344       "run_as_psgi()", as shown below.
345
346       It's possible that we'll change from CGI::PSGI to a different-but-
347       compatible query object for PSGI support in the future, perhaps if
348       CGI.pm adds native PSGI support.
349
350       run_as_psgi()
351
352        my $psgi_aref = $webapp->run_as_psgi;
353
354       Just like "run", but prints no output and returns the data structure
355       required by the PSGI specification. Use this if you want to run the
356       application on top of a PSGI-compatible handler, such as Plack
357       provides.
358
359       If you are just getting started, just use "run()". It's easy to switch
360       to using "run_as_psgi" later.
361
362       Why use "run_as_psgi()"? There are already solutions to run
363       CGI::Application-based projects on several web servers with dozens of
364       plugins.  Running as a PSGI-compatible application provides the ability
365       to run on additional PSGI-compatible servers, as well as providing
366       access to all of the "Middleware" solutions available through the Plack
367       project.
368
369       The structure returned is an arrayref, containing the status code, an
370       arrayref of header key/values and an arrayref containing the body.
371
372        [ 200, [ 'Content-Type' => 'text/html' ], [ $body ] ]
373
374       By default the body is a single scalar, but plugins may modify this to
375       return other value PSGI values.  See "The Response" in PSGI for details
376       about the response format.
377
378       Note that calling "run_as_psgi" only handles the output portion of the
379       PSGI spec. to handle the input, you need to use a CGI.pm-like query
380       object that is PSGI-compliant, such as CGI::PSGI. This query object
381       must provide psgi_header and psgi_redirect methods.
382
383       The final result might look like this:
384
385           use WebApp;
386           use CGI::PSGI;
387
388           my $handler = sub {
389               my $env = shift;
390               my $webapp = WebApp->new({ QUERY => CGI::PSGI->new($env) });
391               $webapp->run_as_psgi;
392           };
393
394   Additional PSGI Return Values
395       The PSGI Specification allows for returning a file handle or a
396       subroutine reference instead of byte strings.  In PSGI mode this is
397       supported directly by CGI::Application.  Have your run mode return a
398       file handle or compatible subref as follows:
399
400               sub returning_a_file_handle {
401                   my $self = shift;
402
403                   $self->header_props(-type => 'text/plain');
404
405               open my $fh, "<", 'test_file.txt' or die "OOPS! $!";
406
407                   return $fh;
408               }
409
410           sub returning_a_subref {
411               my $self = shift;
412
413               $self->header_props(-type => 'text/plain');
414               return sub {
415                  my $writer = shift;
416                  foreach my $i (1..10) {
417                      #sleep 1;
418                      $writer->write("check $i: " . time . "\n");
419                       }
420               };
421           }
422
423   Methods to possibly override
424       CGI::Application implements some methods which are expected to be
425       overridden by implementing them in your sub-class module.  These
426       methods are as follows:
427
428       setup()
429
430       This method is called by the inherited new() constructor method.  The
431       setup() method should be used to define the following property/methods:
432
433           mode_param() - set the name of the run mode CGI param.
434           start_mode() - text scalar containing the default run mode.
435           error_mode() - text scalar containing the error mode.
436           run_modes() - hash table containing mode => function mappings.
437           tmpl_path() - text scalar or array reference containing path(s) to template files.
438
439       Your setup() method may call any of the instance methods of your
440       application.  This function is a good place to define properties
441       specific to your application via the $webapp->param() method.
442
443       Your setup() method might be implemented something like this:
444
445               sub setup {
446                       my $self = shift;
447                       $self->tmpl_path('/path/to/my/templates/');
448                       $self->start_mode('putform');
449                       $self->error_mode('my_error_rm');
450                       $self->run_modes({
451                               'putform'  => 'my_putform_func',
452                               'postdata' => 'my_data_func'
453                       });
454                       $self->param('myprop1');
455                       $self->param('myprop2', 'prop2value');
456                       $self->param('myprop3', ['p3v1', 'p3v2', 'p3v3']);
457               }
458
459       However, often times all that needs to be in setup() is defining your
460       run modes and your start mode. CGI::Application::Plugin::AutoRunmode
461       allows you to do this with a simple syntax, using run mode attributes:
462
463        use CGI::Application::Plugin::AutoRunmode;
464
465        sub show_first : StartRunmode { ... };
466        sub do_next : Runmode { ... }
467
468       teardown()
469
470       If implemented, this method is called automatically after your
471       application runs.  It can be used to clean up after your operations.  A
472       typical use of the teardown() function is to disconnect a database
473       connection which was established in the setup() function.  You could
474       also use the teardown() method to store state information about the
475       application to the server.
476
477       cgiapp_init()
478
479       If implemented, this method is called automatically right before the
480       setup() method is called.  This method provides an optional
481       initialization hook, which improves the object-oriented characteristics
482       of CGI::Application.  The cgiapp_init() method receives, as its
483       parameters, all the arguments which were sent to the new() method.
484
485       An example of the benefits provided by utilizing this hook is creating
486       a custom "application super-class" from which all your web applications
487       would inherit, instead of CGI::Application.
488
489       Consider the following:
490
491         # In MySuperclass.pm:
492         package MySuperclass;
493         use base 'CGI::Application';
494         sub cgiapp_init {
495               my $self = shift;
496               # Perform some project-specific init behavior
497               # such as to load settings from a database or file.
498         }
499
500
501         # In MyApplication.pm:
502         package MyApplication;
503         use base 'MySuperclass';
504         sub setup { ... }
505         sub teardown { ... }
506         # The rest of your CGI::Application-based follows...
507
508       By using CGI::Application and the cgiapp_init() method as illustrated,
509       a suite of applications could be designed to share certain
510       characteristics.  This has the potential for much cleaner code built on
511       object-oriented inheritance.
512
513       cgiapp_prerun()
514
515       If implemented, this method is called automatically right before the
516       selected run mode method is called.  This method provides an optional
517       pre-runmode hook, which permits functionality to be added at the point
518       right before the run mode method is called.  To further leverage this
519       hook, the value of the run mode is passed into cgiapp_prerun().
520
521       Another benefit provided by utilizing this hook is creating a custom
522       "application super-class" from which all your web applications would
523       inherit, instead of CGI::Application.
524
525       Consider the following:
526
527         # In MySuperclass.pm:
528         package MySuperclass;
529         use base 'CGI::Application';
530         sub cgiapp_prerun {
531               my $self = shift;
532               # Perform some project-specific init behavior
533               # such as to implement run mode specific
534               # authorization functions.
535         }
536
537
538         # In MyApplication.pm:
539         package MyApplication;
540         use base 'MySuperclass';
541         sub setup { ... }
542         sub teardown { ... }
543         # The rest of your CGI::Application-based follows...
544
545       By using CGI::Application and the cgiapp_prerun() method as
546       illustrated, a suite of applications could be designed to share certain
547       characteristics.  This has the potential for much cleaner code built on
548       object-oriented inheritance.
549
550       It is also possible, within your cgiapp_prerun() method, to change the
551       run mode of your application.  This can be done via the prerun_mode()
552       method, which is discussed elsewhere in this POD.
553
554       cgiapp_postrun()
555
556       If implemented, this hook will be called after the run mode method has
557       returned its output, but before HTTP headers are generated.  This will
558       give you an opportunity to modify the body and headers before they are
559       returned to the web browser.
560
561       A typical use for this hook is pipelining the output of a CGI-
562       Application through a series of "filter" processors.  For example:
563
564         * You want to enclose the output of all your CGI-Applications in
565           an HTML table in a larger page.
566
567         * Your run modes return structured data (such as XML), which you
568           want to transform using a standard mechanism (such as XSLT).
569
570         * You want to post-process CGI-App output through another system,
571           such as HTML::Mason.
572
573         * You want to modify HTTP headers in a particular way across all
574           run modes, based on particular criteria.
575
576       The cgiapp_postrun() hook receives a reference to the output from your
577       run mode method, in addition to the CGI-App object.  A typical
578       cgiapp_postrun() method might be implemented as follows:
579
580         sub cgiapp_postrun {
581           my $self = shift;
582           my $output_ref = shift;
583
584           # Enclose output HTML table
585           my $new_output = "<table border=1>";
586           $new_output .= "<tr><td> Hello, World! </td></tr>";
587           $new_output .= "<tr><td>". $$output_ref ."</td></tr>";
588           $new_output .= "</table>";
589
590           # Replace old output with new output
591           $$output_ref = $new_output;
592         }
593
594       Obviously, with access to the CGI-App object you have full access to
595       use all the methods normally available in a run mode.  You could, for
596       example, use "load_tmpl()" to replace the static HTML in this example
597       with HTML::Template.  You could change the HTTP headers (via
598       "header_type()" and "header_props()" methods) to set up a redirect.
599       You could also use the objects properties to apply changes only under
600       certain circumstance, such as a in only certain run modes, and when a
601       "param()" is a particular value.
602
603       cgiapp_get_query()
604
605        my $q = $webapp->cgiapp_get_query;
606
607       Override this method to retrieve the query object if you wish to use a
608       different query interface instead of CGI.pm.
609
610       CGI.pm is only loaded if it is used on a given request.
611
612       If you can use an alternative to CGI.pm, it needs to have some
613       compatibility with the CGI.pm API. For normal use, just having a
614       compatible "param" method should be sufficient.
615
616       If you use the "path_info" option to the mode_param() method, then we
617       will call the "path_info()" method on the query object.
618
619       If you use the "Dump" method in CGI::Application, we will call the
620       "Dump" and "escapeHTML" methods on the query object.
621
622   Essential Application Methods
623       The following methods are inherited from CGI::Application, and are
624       available to be called by your application within your Application
625       Module. They are called essential because you will use all are most of
626       them to get any application up and running.  These functions are listed
627       in alphabetical order.
628
629       load_tmpl()
630
631           my $tmpl_obj = $webapp->load_tmpl;
632           my $tmpl_obj = $webapp->load_tmpl('some.html');
633           my $tmpl_obj = $webapp->load_tmpl( \$template_content );
634           my $tmpl_obj = $webapp->load_tmpl( FILEHANDLE );
635
636       This method takes the name of a template file, a reference to template
637       data or a FILEHANDLE and returns an HTML::Template object. If the
638       filename is undefined or missing, CGI::Application will default to
639       trying to use the current run mode name, plus the extension ".html".
640
641       If you use the default template naming system, you should also use
642       CGI::Application::Plugin::Forward, which simply helps to keep the
643       current name accurate when you pass control from one run mode to
644       another.
645
646       ( For integration with other template systems and automated template
647       names, see "Alternatives to load_tmpl() below. )
648
649       When you pass in a filename, the HTML::Template->new_file() constructor
650       is used for create the object.  When you pass in a reference to the
651       template content, the HTML::Template->new_scalar_ref() constructor is
652       used and when you pass in a filehandle, the
653       HTML::Template->new_filehandle() constructor is used.
654
655       Refer to HTML::Template for specific usage of HTML::Template.
656
657       If tmpl_path() has been specified, load_tmpl() will set the
658       HTML::Template "path" option to the path(s) provided.  This further
659       assists in encapsulating template usage.
660
661       The load_tmpl() method will pass any extra parameters sent to it
662       directly to HTML::Template->new_file() (or new_scalar_ref() or
663       new_filehandle()).  This will allow the HTML::Template object to be
664       further customized:
665
666           my $tmpl_obj = $webapp->load_tmpl('some_other.html',
667                die_on_bad_params => 0,
668                cache => 1
669           );
670
671       Note that if you want to pass extra arguments but use the default
672       template name, you still need to provide a name of "undef":
673
674           my $tmpl_obj = $webapp->load_tmpl(undef,
675                die_on_bad_params => 0,
676                cache => 1
677           );
678
679       Alternatives to load_tmpl()
680
681       If your application requires more specialized behavior than this, you
682       can always replace it by overriding load_tmpl() by implementing your
683       own load_tmpl() in your CGI::Application sub-class application module.
684
685       First, you may want to check out the template related plugins.
686
687       CGI::Application::Plugin::TT focuses just on Template Toolkit
688       integration, and features pre-and-post features, singleton support and
689       more.
690
691       CGI::Application::Plugin::Stream can help if you want to return a
692       stream and not a file. It features a simple syntax and MIME-type
693       detection.
694
695       specifying the template class with html_tmpl_class()
696
697       You may specify an API-compatible alternative to HTML::Template by
698       setting a new "html_tmpl_class()":
699
700         $self->html_tmpl_class('HTML::Template::Dumper');
701
702       The default is "HTML::Template". The alternate class should provide at
703       least the following parts of the HTML::Template API:
704
705        $t = $class->new( scalarref => ... );  # If you use scalarref templates
706        $t = $class->new( filehandle => ... ); # If you use filehandle templates
707        $t = $class->new( filename => ... );
708        $t->param(...);
709
710       Here's an example case allowing you to precisely test what's sent to
711       your templates:
712
713           $ENV{CGI_APP_RETURN_ONLY} = 1;
714           my $webapp = WebApp->new;
715              $webapp->html_tmpl_class('HTML::Template::Dumper');
716           my $out_str = $webapp->run;
717           my $tmpl_href = eval "$out_str";
718
719           # Now Precisely test what would be set to the template
720           is ($tmpl_href->{pet_name}, 'Daisy', "Daisy is sent template");
721
722       This is a powerful technique because HTML::Template::Dumper loads and
723       considers the template file that would actually be used. If the
724       'pet_name' token was missing in the template, the above test would
725       fail. So, you are testing both your code and your templates in a much
726       more precise way than using simple regular expressions to see if the
727       string "Daisy" appeared somewhere on the page.
728
729       The load_tmpl() callback
730
731       Plugin authors will be interested to know that you can register a
732       callback that will be executed just before load_tmpl() returns:
733
734         $self->add_callback('load_tmpl',\&your_method);
735
736       When "your_method()" is executed, it will be passed three arguments:
737
738        1. A hash reference of the extra params passed into C<load_tmpl>
739        2. Followed by a hash reference to template parameters.
740           With both of these, you can modify them by reference to affect
741           values that are actually passed to the new() and param() methods of the
742           template object.
743        3. The name of the template file.
744
745       Here's an example stub for a load_tmpl() callback:
746
747           sub my_load_tmpl_callback {
748               my ($c, $ht_params, $tmpl_params, $tmpl_file) = @_
749               # modify $ht_params or $tmpl_params by reference...
750           }
751
752       param()
753
754           $webapp->param('pname', $somevalue);
755
756       The param() method provides a facility through which you may set
757       application instance properties which are accessible throughout your
758       application.
759
760       The param() method may be used in two basic ways.  First, you may use
761       it to get or set the value of a parameter:
762
763           $webapp->param('scalar_param', '123');
764           my $scalar_param_values = $webapp->param('some_param');
765
766       Second, when called in the context of an array, with no parameter name
767       specified, param() returns an array containing all the parameters which
768       currently exist:
769
770           my @all_params = $webapp->param();
771
772       The param() method also allows you to set a bunch of parameters at once
773       by passing in a hash (or hashref):
774
775           $webapp->param(
776               'key1' => 'val1',
777               'key2' => 'val2',
778               'key3' => 'val3',
779           );
780
781       The param() method enables a very valuable system for customizing your
782       applications on a per-instance basis.  One Application Module might be
783       instantiated by different Instance Scripts.  Each Instance Script might
784       set different values for a set of parameters.  This allows similar
785       applications to share a common code-base, but behave differently.  For
786       example, imagine a mail form application with a single Application
787       Module, but multiple Instance Scripts.  Each Instance Script might
788       specify a different recipient.  Another example would be a web bulletin
789       boards system.  There could be multiple boards, each with a different
790       topic and set of administrators.
791
792       The new() method provides a shortcut for specifying a number of run-
793       time parameters at once.  Internally, CGI::Application calls the
794       param() method to set these properties.  The param() method is a
795       powerful tool for greatly increasing your application's re-usability.
796
797       query()
798
799           my $q = $webapp->query();
800           my $remote_user = $q->remote_user();
801
802       This method retrieves the CGI.pm query object which has been created by
803       instantiating your Application Module.  For details on usage of this
804       query object, refer to CGI.  CGI::Application is built on the CGI
805       module.  Generally speaking, you will want to become very familiar with
806       CGI.pm, as you will use the query object whenever you want to interact
807       with form data.
808
809       When the new() method is called, a CGI query object is automatically
810       created.  If, for some reason, you want to use your own CGI query
811       object, the new() method supports passing in your existing query object
812       on construction using the QUERY attribute.
813
814       There are a few rare situations where you want your own query object to
815       be used after your Application Module has already been constructed. In
816       that case you can pass it to c<query()> like this:
817
818           $webapp->query($new_query_object);
819           my $q = $webapp->query(); # now uses $new_query_object
820
821       run_modes()
822
823           # The common usage: an arrayref of run mode names that exactly match subroutine names
824           $webapp->run_modes([qw/
825               form_display
826               form_process
827           /]);
828
829          # With a hashref, use a different name or a code ref
830          $webapp->run_modes(
831                  'mode1' => 'some_sub_by_name',
832                  'mode2' => \&some_other_sub_by_ref
833           );
834
835       This accessor/mutator specifies the dispatch table for the application
836       states, using the syntax examples above. It returns the dispatch table
837       as a hash.
838
839       The run_modes() method may be called more than once.  Additional values
840       passed into run_modes() will be added to the run modes table.  In the
841       case that an existing run mode is re-defined, the new value will
842       override the existing value.  This behavior might be useful for
843       applications which are created via inheritance from another
844       application, or some advanced application which modifies its own
845       capabilities based on user input.
846
847       The run() method uses the data in this table to send the application to
848       the correct function as determined by reading the CGI parameter
849       specified by mode_param() (defaults to 'rm' for "Run Mode").  These
850       functions are referred to as "run mode methods".
851
852       The hash table set by this method is expected to contain the mode name
853       as a key.  The value should be either a hard reference (a subref) to
854       the run mode method which you want to be called when the application
855       enters the specified run mode, or the name of the run mode method to be
856       called:
857
858           'mode_name_by_ref'  => \&mode_function
859           'mode_name_by_name' => 'mode_function'
860
861       The run mode method specified is expected to return a block of text
862       (e.g.: HTML) which will eventually be sent back to the web browser.
863       The run mode method may return its block of text as a scalar or a
864       scalar-ref.
865
866       An advantage of specifying your run mode methods by name instead of by
867       reference is that you can more easily create derivative applications
868       using inheritance.  For instance, if you have a new application which
869       is exactly the same as an existing application with the exception of
870       one run mode, you could simply inherit from that other application and
871       override the run mode method which is different.  If you specified your
872       run mode method by reference, your child class would still use the
873       function from the parent class.
874
875       An advantage of specifying your run mode methods by reference instead
876       of by name is performance.  Dereferencing a subref is faster than
877       eval()-ing a code block.  If run-time performance is a critical issue,
878       specify your run mode methods by reference and not by name.  The speed
879       differences are generally small, however, so specifying by name is
880       preferred.
881
882       Specifying the run modes by array reference:
883
884           $webapp->run_modes([ 'mode1', 'mode2', 'mode3' ]);
885
886       This is the same as using a hash, with keys equal to values
887
888           $webapp->run_modes(
889               'mode1' => 'mode1',
890               'mode2' => 'mode2',
891               'mode3' => 'mode3'
892           );
893
894       Often, it makes good organizational sense to have your run modes map to
895       methods of the same name.  The array-ref interface provides a shortcut
896       to that behavior while reducing verbosity of your code.
897
898       Note that another importance of specifying your run modes in either a
899       hash or array-ref is to assure that only those Perl methods which are
900       specifically designated may be called via your application.
901       Application environments which don't specify allowed methods and
902       disallow all others are insecure, potentially opening the door to
903       allowing execution of arbitrary code.  CGI::Application maintains a
904       strict "default-deny" stance on all method invocation, thereby allowing
905       secure applications to be built upon it.
906
907       IMPORTANT NOTE ABOUT RUN MODE METHODS
908
909       Your application should *NEVER* print() to STDOUT.  Using print() to
910       send output to STDOUT (including HTTP headers) is exclusively the
911       domain of the inherited run() method.  Breaking this rule is a common
912       source of errors.  If your program is erroneously sending content
913       before your HTTP header, you are probably breaking this rule.
914
915       THE RUN MODE OF LAST RESORT: "AUTOLOAD"
916
917       If CGI::Application is asked to go to a run mode which doesn't exist it
918       will usually croak() with errors.  If this is not your desired
919       behavior, it is possible to catch this exception by implementing a run
920       mode with the reserved name "AUTOLOAD":
921
922         $self->run_modes(
923               "AUTOLOAD" => \&catch_my_exception
924         );
925
926       Before CGI::Application calls croak() it will check for the existence
927       of a run mode called "AUTOLOAD".  If specified, this run mode will in
928       invoked just like a regular run mode, with one exception:  It will
929       receive, as an argument, the name of the run mode which invoked it:
930
931         sub catch_my_exception {
932               my $self = shift;
933               my $intended_runmode = shift;
934
935               my $output = "Looking for '$intended_runmode', but found 'AUTOLOAD' instead";
936               return $output;
937         }
938
939       This functionality could be used for a simple human-readable error
940       screen, or for more sophisticated application behaviors.
941
942       start_mode()
943
944           $webapp->start_mode('mode1');
945
946       The start_mode contains the name of the mode as specified in the
947       run_modes() table.  Default mode is "start".  The mode key specified
948       here will be used whenever the value of the CGI form parameter
949       specified by mode_param() is not defined.  Generally, this is the first
950       time your application is executed.
951
952       tmpl_path()
953
954           $webapp->tmpl_path('/path/to/some/templates/');
955
956       This access/mutator method sets the file path to the directory (or
957       directories) where the templates are stored.  It is used by load_tmpl()
958       to find the template files, using HTML::Template's "path" option. To
959       set the path you can either pass in a text scalar or an array reference
960       of multiple paths.
961
962   More Application Methods
963       You can skip this section if you are just getting started.
964
965       The following additional methods are inherited from CGI::Application,
966       and are available to be called by your application within your
967       Application Module.  These functions are listed in alphabetical order.
968
969       delete()
970
971           $webapp->delete('my_param');
972
973       The delete() method is used to delete a parameter that was previously
974       stored inside of your application either by using the PARAMS hash that
975       was passed in your call to new() or by a call to the param() method.
976       This is similar to the delete() method of CGI.pm. It is useful if your
977       application makes decisions based on the existence of certain params
978       that may have been removed in previous sections of your app or simply
979       to clean-up your param()s.
980
981       dump()
982
983           print STDERR $webapp->dump();
984
985       The dump() method is a debugging function which will return a chunk of
986       text which contains all the environment and web form data of the
987       request, formatted nicely for human readability.  Useful for outputting
988       to STDERR.
989
990       dump_html()
991
992           my $output = $webapp->dump_html();
993
994       The dump_html() method is a debugging function which will return a
995       chunk of text which contains all the environment and web form data of
996       the request, formatted nicely for human readability via a web browser.
997       Useful for outputting to a browser. Please consider the security
998       implications of using this in production code.
999
1000       error_mode()
1001
1002           $webapp->error_mode('my_error_rm');
1003
1004       If the runmode dies for whatever reason, "run() will" see if you have
1005       set a value for "error_mode()". If you have, "run()" will call that
1006       method as a run mode, passing $@ as the only parameter.
1007
1008       Plugins authors will be interested to know that just before
1009       "error_mode()" is called, the "error" hook will be executed, with the
1010       error message passed in as the only parameter.
1011
1012       No "error_mode" is defined by default.  The death of your
1013       "error_mode()" run mode is not trapped, so you can also use it to die
1014       in your own special way.
1015
1016       For a complete integrated logging solution, check out
1017       CGI::Application::Plugin::LogDispatch.
1018
1019       get_current_runmode()
1020
1021           $webapp->get_current_runmode();
1022
1023       The "get_current_runmode()" method will return a text scalar containing
1024       the name of the run mode which is currently being executed.  If the run
1025       mode has not yet been determined, such as during setup(), this method
1026       will return undef.
1027
1028       header_add()
1029
1030           # add or replace the 'type' header
1031           $webapp->header_add( -type => 'image/png' );
1032
1033           - or -
1034
1035           # add an additional cookie
1036           $webapp->header_add(-cookie=>[$extra_cookie]);
1037
1038       The "header_add()" method is used to add one or more headers to the
1039       outgoing response headers.  The parameters will eventually be passed on
1040       to the CGI.pm header() method, so refer to the CGI docs for exact usage
1041       details.
1042
1043       Unlike calling "header_props()", "header_add()" will preserve any
1044       existing headers. If a scalar value is passed to "header_add()" it will
1045       replace the existing value for that key.
1046
1047       If an array reference is passed as a value to "header_add()", values in
1048       that array ref will be appended to any existing values for that key.
1049       This is primarily useful for setting an additional cookie after one has
1050       already been set.
1051
1052       header_props()
1053
1054           # Set a complete set of headers
1055           %set_headers = $webapp->header_props(-type=>'image/gif',-expires=>'+3d');
1056
1057           # clobber / reset all headers
1058           %set_headers = $webapp->header_props({});
1059
1060           # Just retrieve the headers
1061           %set_headers = $webapp->header_props();
1062
1063       The "header_props()" method expects a hash of CGI.pm-compatible HTTP
1064       header properties.  These properties will be passed directly to the
1065       "header()" or "redirect()" methods of the query() object. Refer to the
1066       docs of your query object for details. (Be default, it's CGI.pm).
1067
1068       Calling header_props with an empty hashref clobber any existing headers
1069       that have previously set.
1070
1071       "header_props()" returns a hash of all the headers that have currently
1072       been set. It can be called with no arguments just to get the hash
1073       current headers back.
1074
1075       To add additional headers later without clobbering the old ones, see
1076       "header_add()".
1077
1078       IMPORTANT NOTE REGARDING HTTP HEADERS
1079
1080       It is through the "header_props()" and "header_add()" method that you
1081       may modify the outgoing HTTP headers.  This is necessary when you want
1082       to set a cookie, set the mime type to something other than "text/html",
1083       or perform a redirect.  The header_props() method works in conjunction
1084       with the header_type() method.  The value contained in header_type()
1085       determines if we use CGI::header() or CGI::redirect().  The content of
1086       header_props() is passed as an argument to whichever CGI.pm function is
1087       called.
1088
1089       Understanding this relationship is important if you wish to manipulate
1090       the HTTP header properly.
1091
1092       header_type()
1093
1094           $webapp->header_type('redirect');
1095           $webapp->header_type('none');
1096
1097       This method used to declare that you are setting a redirection header,
1098       or that you want no header to be returned by the framework.
1099
1100       The value of 'header' is almost never used, as it is the default.
1101
1102       Example of redirecting:
1103
1104         sub some_redirect_mode {
1105           my $self = shift;
1106           # do stuff here....
1107           $self->header_type('redirect');
1108           $self->header_props(-url=>  "http://site/path/doc.html" );
1109         }
1110
1111       To simplify that further, use CGI::Application::Plugin::Redirect:
1112
1113           return $self->redirect('http://www.example.com/');
1114
1115       Setting the header to 'none' may be useful if you are streaming
1116       content.  In other contexts, it may be more useful to set
1117       "$ENV{CGI_APP_RETURN_ONLY} = 1;", which suppresses all printing,
1118       including headers, and returns the output instead.
1119
1120       That's commonly used for testing, or when using CGI::Application as a
1121       controller for a cron script!
1122
1123       mode_param()
1124
1125        # Name the CGI form parameter that contains the run mode name.
1126        # This is the default behavior, and is often sufficient.
1127        $webapp->mode_param('rm');
1128
1129        # Set the run mode name directly from a code ref
1130        $webapp->mode_param(\&some_method);
1131
1132        # Alternate interface, which allows you to set the run
1133        # mode name directly from $ENV{PATH_INFO}.
1134        $webapp->mode_param(
1135               path_info=> 1,
1136               param =>'rm'
1137        );
1138
1139       This accessor/mutator method is generally called in the setup() method.
1140       It is used to help determine the run mode to call. There are three
1141       options for calling it.
1142
1143        $webapp->mode_param('rm');
1144
1145       Here, a CGI form parameter is named that will contain the name of the
1146       run mode to use. This is the default behavior, with 'rm' being the
1147       parameter named used.
1148
1149        $webapp->mode_param(\&some_method);
1150
1151       Here a code reference is provided. It will return the name of the run
1152       mode to use directly. Example:
1153
1154        sub some_method {
1155          my $self = shift;
1156          return 'run_mode_x';
1157        }
1158
1159       This would allow you to programmatically set the run mode based on
1160       arbitrary logic.
1161
1162        $webapp->mode_param(
1163               path_info=> 1,
1164               param =>'rm'
1165        );
1166
1167       This syntax allows you to easily set the run mode from $ENV{PATH_INFO}.
1168       It will try to set the run mode from the first part of $ENV{PATH_INFO}
1169       (before the first "/"). To specify that you would rather get the run
1170       mode name from the 2nd part of $ENV{PATH_INFO}:
1171
1172        $webapp->mode_param( path_info=> 2 );
1173
1174       This also demonstrates that you don't need to pass in the "param" hash
1175       key. It will still default to "rm".
1176
1177       You can also set "path_info" to a negative value. This works just like
1178       a negative list index: if it is -1 the run mode name will be taken from
1179       the last part of $ENV{PATH_INFO}, if it is -2, the one before that, and
1180       so on.
1181
1182       If no run mode is found in $ENV{PATH_INFO}, it will fall back to
1183       looking in the value of a the CGI form field defined with 'param', as
1184       described above.  This allows you to use the convenient $ENV{PATH_INFO}
1185       trick most of the time, but also supports the edge cases, such as when
1186       you don't know what the run mode will be ahead of time and want to
1187       define it with JavaScript.
1188
1189       More about $ENV{PATH_INFO}.
1190
1191       Using $ENV{PATH_INFO} to name your run mode creates a clean separation
1192       between the form variables you submit and how you determine the
1193       processing run mode. It also creates URLs that are more search engine
1194       friendly. Let's look at an example form submission using this syntax:
1195
1196               <form action="/cgi-bin/instance.cgi/edit_form" method=post>
1197                       <input type="hidden" name="breed_id" value="4">
1198
1199       Here the run mode would be set to "edit_form". Here's another example
1200       with a query string:
1201
1202               /cgi-bin/instance.cgi/edit_form?breed_id=2
1203
1204       This demonstrates that you can use $ENV{PATH_INFO} and a query string
1205       together without problems. $ENV{PATH_INFO} is defined as part of the
1206       CGI specification should be supported by any web server that supports
1207       CGI scripts.
1208
1209       prerun_mode()
1210
1211           $webapp->prerun_mode('new_run_mode');
1212
1213       The prerun_mode() method is an accessor/mutator which can be used
1214       within your cgiapp_prerun() method to change the run mode which is
1215       about to be executed.  For example, consider:
1216
1217         # In WebApp.pm:
1218         package WebApp;
1219         use base 'CGI::Application';
1220         sub cgiapp_prerun {
1221               my $self = shift;
1222
1223               # Get the web user name, if any
1224               my $q = $self->query();
1225               my $user = $q->remote_user();
1226
1227               # Redirect to login, if necessary
1228               unless ($user) {
1229                       $self->prerun_mode('login');
1230               }
1231         }
1232
1233       In this example, the web user will be forced into the "login" run mode
1234       unless they have already logged in.  The prerun_mode() method permits a
1235       scalar text string to be set which overrides whatever the run mode
1236       would otherwise be.
1237
1238       The use of prerun_mode() within cgiapp_prerun() differs from setting
1239       mode_param() to use a call-back via subroutine reference.  It differs
1240       because cgiapp_prerun() allows you to selectively set the run mode
1241       based on some logic in your cgiapp_prerun() method.  The call-back
1242       facility of mode_param() forces you to entirely replace
1243       CGI::Application's mechanism for determining the run mode with your own
1244       method.  The prerun_mode() method should be used in cases where you
1245       want to use CGI::Application's normal run mode switching facility, but
1246       you want to make selective changes to the mode under specific
1247       conditions.
1248
1249       Note:  The prerun_mode() method may ONLY be called in the context of a
1250       cgiapp_prerun() method.  Your application will die() if you call
1251       prerun_mode() elsewhere, such as in setup() or a run mode method.
1252
1253   Dispatching Clean URIs to run modes
1254       Modern web frameworks dispense with cruft in URIs, providing in clean
1255       URIs instead. Instead of:
1256
1257        /cgi-bin/item.cgi?rm=view&id=15
1258
1259       A clean URI to describe the same resource might be:
1260
1261        /item/15/view
1262
1263       The process of mapping these URIs to run modes is called dispatching
1264       and is handled by CGI::Application::Dispatch. Dispatching is not
1265       required and is a layer you can fairly easily add to an application
1266       later.
1267
1268   Offline website development
1269       You can work on your CGI::Application project on your desktop or laptop
1270       without installing a full-featured web-server like Apache. Instead,
1271       install CGI::Application::Server from CPAN. After a few minutes of
1272       setup, you'll have your own private application server up and running.
1273
1274   Automated Testing
1275       Test::WWW::Mechanize::CGIApp allows functional testing of a
1276       CGI::App-based project without starting a web server.
1277       Test::WWW::Mechanize could be used to test the app through a real web
1278       server.
1279
1280       Direct testing is also easy. CGI::Application will normally print the
1281       output of it's run modes directly to STDOUT. This can be suppressed
1282       with an environment variable, CGI_APP_RETURN_ONLY. For example:
1283
1284         $ENV{CGI_APP_RETURN_ONLY} = 1;
1285         $output = $webapp->run();
1286         like($output, qr/good/, "output is good");
1287
1288       Examples of this style can be seen in our own test suite.
1289

PLUG-INS

1291       CGI::Application has a plug-in architecture that is easy to use and
1292       easy to develop new plug-ins for.
1293
1294   Recommended Plug-ins
1295       The following plugins are recommended for general purpose web/db
1296       development:
1297
1298       ·   CGI::Application::Plugin::Redirect - is a simple plugin to provide
1299           a shorter syntax for executing a redirect.
1300
1301       ·   CGI::Application::Plugin::ConfigAuto - Keeping your config details
1302           in a separate file is recommended for every project. This one
1303           integrates with Config::Auto. Several more config plugin options
1304           are listed below.
1305
1306       ·   CGI::Application::Plugin::DBH - Provides easy management of one or
1307           more database handles and can delay making the database connection
1308           until the moment it is actually used.
1309
1310       ·   CGI::Application::Plugin::FillInForm - makes it a breeze to fill in
1311           an HTML form from data originating from a CGI query or a database
1312           record.
1313
1314       ·   CGI::Application::Plugin::Session - For a project that requires
1315           session management, this plugin provides a useful wrapper around
1316           CGI::Session
1317
1318       ·   CGI::Application::Plugin::ValidateRM - Integration with
1319           Data::FormValidator and HTML::FillInForm
1320
1321   More plug-ins
1322       Many more plugins are available as alternatives and for specific uses.
1323       For a current complete list, please consult CPAN:
1324
1325       http://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin
1326
1327       ·   CGI::Application::Plugin::AnyTemplate - Use any templating system
1328           from within CGI::Application using a unified interface
1329
1330       ·   CGI::Application::Plugin::Apache - Use Apache::* modules without
1331           interference
1332
1333       ·   CGI::Application::Plugin::AutoRunmode - Automatically register
1334           runmodes
1335
1336       ·   CGI::Application::Plugin::Config::Context - Integration with
1337           Config::Context.
1338
1339       ·   CGI::Application::Plugin::Config::General - Integration with
1340           Config::General.
1341
1342       ·   CGI::Application::Plugin::Config::Simple - Integration with
1343           Config::Simple.
1344
1345       ·   CGI::Application::Plugin::CompressGzip - Add Gzip compression
1346
1347       ·   CGI::Application::Plugin::LogDispatch - Integration with
1348           Log::Dispatch
1349
1350       ·   CGI::Application::Plugin::Stream - Help stream files to the browser
1351
1352       ·   CGI::Application::Plugin::TemplateRunner - Allows for more of an
1353           ASP-style code structure, with the difference that code and HTML
1354           for each screen are in separate files.
1355
1356       ·   CGI::Application::Plugin::TT - Use Template::Toolkit as an
1357           alternative to HTML::Template.
1358
1359       Consult each plug-in for the exact usage syntax.
1360
1361   Writing Plug-ins
1362       Writing plug-ins is simple. Simply create a new package, and export the
1363       methods that you want to become part of a CGI::Application project. See
1364       CGI::Application::Plugin::ValidateRM for an example.
1365
1366       In order to avoid namespace conflicts within a CGI::Application object,
1367       plugin developers are recommended to use a unique prefix, such as the
1368       name of plugin package, when storing information. For instance:
1369
1370        $app->{__PARAM} = 'foo'; # BAD! Could conflict.
1371        $app->{'MyPlugin::Module::__PARAM'} = 'foo'; # Good.
1372        $app->{'MyPlugin::Module'}{__PARAM} = 'foo'; # Good.
1373
1374   Writing Advanced Plug-ins - Using callbacks
1375       When writing a plug-in, you may want some action to happen
1376       automatically at a particular stage, such as setting up a database
1377       connection or initializing a session. By using these 'callback'
1378       methods, you can register a subroutine to run at a particular phase,
1379       accomplishing this goal.
1380
1381       Callback Examples
1382
1383         # register a callback to the standard CGI::Application hooks
1384         #   one of 'init', 'prerun', 'postrun', 'teardown' or 'load_tmpl'
1385         # As a plug-in author, this is probably the only method you need.
1386
1387         # Class-based: callback will persist for all runs of the application
1388         $class->add_callback('init', \&some_other_method);
1389
1390         # Object-based: callback will only last for lifetime of this object
1391         $self->add_callback('prerun', \&some_method);
1392
1393         # If you want to create a new hook location in your application,
1394         # You'll need to know about the following two methods to create
1395         # the hook and call it.
1396
1397         # Create a new hook
1398         $self->new_hook('pretemplate');
1399
1400         # Then later execute all the callbacks registered at this hook
1401         $self->call_hook('pretemplate');
1402
1403       Callback Methods
1404
1405       add_callback()
1406
1407               $self->add_callback ('teardown', \&callback);
1408               $class->add_callback('teardown', 'method');
1409
1410       The add_callback method allows you to register a callback function that
1411       is to be called at the given stage of execution.  Valid hooks include
1412       'init', 'prerun', 'postrun' and 'teardown', 'load_tmpl', and any other
1413       hooks defined using the "new_hook" method.
1414
1415       The callback should be a reference to a subroutine or the name of a
1416       method.
1417
1418       If multiple callbacks are added to the same hook, they will all be
1419       executed one after the other.  The exact order depends on which class
1420       installed each callback, as described below under Callback Ordering.
1421
1422       Callbacks can either be object-based or class-based, depending upon
1423       whether you call "add_callback" as an object method or a class method:
1424
1425               # add object-based callback
1426               $self->add_callback('teardown', \&callback);
1427
1428               # add class-based callbacks
1429               $class->add_callback('teardown', \&callback);
1430               My::Project->add_callback('teardown', \&callback);
1431
1432       Object-based callbacks are stored in your web application's $c object;
1433       at the end of the request when the $c object goes out of scope, the
1434       callbacks are gone too.
1435
1436       Object-based callbacks are useful for one-time tasks that apply only to
1437       the current running application.  For instance you could install a
1438       "teardown" callback to trigger a long-running process to execute at the
1439       end of the current request, after all the HTML has been sent to the
1440       browser.
1441
1442       Class-based callbacks survive for the duration of the running Perl
1443       process.  (In a persistent environment such as "mod_perl" or
1444       "PersistentPerl", a single Perl process can serve many web requests.)
1445
1446       Class-based callbacks are useful for plugins to add features to all web
1447       applications.
1448
1449       Another feature of class-based callbacks is that your plugin can create
1450       hooks and add callbacks at any time - even before the web application's
1451       $c object has been initialized.  A good place to do this is in your
1452       plugin's "import" subroutine:
1453
1454               package CGI::Application::Plugin::MyPlugin;
1455               use base 'Exporter';
1456               sub import {
1457                       my $caller = scalar(caller);
1458                       $caller->add_callback('init', 'my_setup');
1459                       goto &Exporter::import;
1460               }
1461
1462       Notice that "$caller->add_callback" installs the callback on behalf of
1463       the module that contained the line:
1464
1465               use CGI::Application::Plugin::MyPlugin;
1466
1467       new_hook(HOOK)
1468
1469           $self->new_hook('pretemplate');
1470
1471       The "new_hook()" method can be used to create a new location for
1472       developers to register callbacks.  It takes one argument, a hook name.
1473       The hook location is created if it does not already exist. A true value
1474       is always returned.
1475
1476       For an example, CGI::Application::Plugin::TT adds hooks before and
1477       after every template is processed.
1478
1479       See "call_hook(HOOK)" for more details about how hooks are called.
1480
1481       call_hook(HOOK)
1482
1483           $self->call_hook('pretemplate', @args);
1484
1485       The "call_hook" method is used to executed the callbacks that have been
1486       registered at the given hook.  It is used in conjunction with the
1487       "new_hook" method which allows you to create a new hook location.
1488
1489       The first argument to "call_hook" is the hook name. Any remaining
1490       arguments are passed to every callback executed at the hook location.
1491       So, a stub for a callback at the 'pretemplate' hook would look like
1492       this:
1493
1494        sub my_hook {
1495           my ($c,@args) = @_;
1496           # ....
1497        }
1498
1499       Note that hooks are semi-public locations. Calling a hook means
1500       executing callbacks that were registered to that hook by the current
1501       object and also those registered by any of the current object's parent
1502       classes.  See below for the exact ordering.
1503
1504       Callback Ordering
1505
1506       Object-based callbacks are run before class-based callbacks.
1507
1508       The order of class-based callbacks is determined by the inheritance
1509       tree of the running application. The built-in methods of "cgiapp_init",
1510       "cgiapp_prerun", "cgiapp_postrun", and "teardown" are also executed
1511       this way, according to the ordering below.
1512
1513       In a persistent environment, there might be a lot of applications in
1514       memory at the same time.  For instance:
1515
1516               CGI::Application
1517                 Other::Project   # uses CGI::Application::Plugin::Baz
1518                        Other::App    # uses CGI::Application::Plugin::Bam
1519
1520                 My::Project      # uses CGI::Application::Plugin::Foo
1521                        My::App       # uses CGI::Application::Plugin::Bar
1522
1523       Suppose that each of the above plugins each added a callback to be run
1524       at the 'init' stage:
1525
1526               Plugin                           init callback
1527               ------                           -------------
1528               CGI::Application::Plugin::Baz    baz_startup
1529               CGI::Application::Plugin::Bam    bam_startup
1530
1531               CGI::Application::Plugin::Foo    foo_startup
1532               CGI::Application::Plugin::Bar    bar_startup
1533
1534       When "My::App" runs, only "foo_callback" and "bar_callback" will run.
1535       The other callbacks are skipped.
1536
1537       The @ISA list of "My::App" is:
1538
1539               My::App
1540               My::Project
1541               CGI::Application
1542
1543       This order determines the order of callbacks run.
1544
1545       When "call_hook('init')" is run on a "My::App" application, callbacks
1546       installed by these modules are run in order, resulting in:
1547       "bar_startup", "foo_startup", and then finally "cgiapp_init".
1548
1549       If a single class installs more than one callback at the same hook,
1550       then these callbacks are run in the order they were registered (FIFO).
1551

COMMUNITY

1553       Therese are primary resources available for those who wish to learn
1554       more about CGI::Application and discuss it with others.
1555
1556       Wiki
1557
1558       This is a community built and maintained resource that anyone is
1559       welcome to contribute to. It contains a number of articles of its own
1560       and links to many other CGI::Application related pages:
1561
1562       <http://www.cgi-app.org>
1563
1564       Support Mailing List
1565
1566       If you have any questions, comments, bug reports or feature
1567       suggestions, post them to the support mailing list!  To join the
1568       mailing list, visit http://lists.openlib.org/mailman/listinfo/cgiapp
1569
1570       Source Code
1571
1572       This project is managed using git and is available on Github:
1573
1574       <https://github.com/MartinMcGrath/CGI--Application>
1575

SEE ALSO

1577       o   CGI
1578
1579       o   HTML::Template
1580
1581       o   CGI::Application::Framework - A full-featured web application based
1582           on CGI::Application.  http://www.cafweb.org/
1583

MORE READING

1585       If you're interested in finding out more about CGI::Application, the
1586       following articles are available on Perl.com:
1587
1588           Using CGI::Application
1589           http://www.perl.com/pub/a/2001/06/05/cgi.html
1590
1591           Rapid Website Development with CGI::Application
1592           http://www.perl.com/pub/a/2006/10/19/cgi_application.html
1593
1594       Thanks to O'Reilly for publishing these articles, and for the
1595       incredible value they provide to the Perl community!
1596

AUTHOR

1598       Jesse Erlbaum <jesse@erlbaum.net>
1599
1600       Mark Stosberg has served as a co-maintainer since version 3.2, Martin
1601       McGrath became a co-maintainer as of version 4.51, with the help of the
1602       numerous contributors documented in the Changes file.
1603

CREDITS

1605       CGI::Application was originally developed by The Erlbaum Group, a
1606       software engineering and consulting firm in New York City.
1607
1608       Thanks to Vanguard Media (http://www.vm.com) for funding the initial
1609       development of this library and for encouraging Jesse Erlbaum to
1610       release it to the world.
1611
1612       Many thanks to Sam Tregar (author of the most excellent HTML::Template
1613       module!) for his innumerable contributions to this module over the
1614       years, and most of all for getting me off my ass to finally get this
1615       thing up on CPAN!
1616
1617       Many other people have contributed specific suggestions or patches,
1618       which are documented in the "Changes" file.
1619
1620       Thanks also to all the members of the CGI-App mailing list!  Your
1621       ideas, suggestions, insights (and criticism!) have helped shape this
1622       module immeasurably.  (To join the mailing list, visit
1623       http://lists.openlib.org/mailman/listinfo/cgiapp )
1624

LICENSE

1626       CGI::Application : Framework for building reusable web-applications
1627       Copyright (C) 2000-2003 Jesse Erlbaum <jesse@erlbaum.net>
1628
1629       This module is free software; you can redistribute it and/or modify it
1630       under the terms of either:
1631
1632       a) the GNU General Public License as published by the Free Software
1633       Foundation; either version 1, or (at your option) any later version,
1634
1635       or
1636
1637       b) the "Artistic License" which comes with this module.
1638
1639       This program is distributed in the hope that it will be useful, but
1640       WITHOUT ANY WARRANTY; without even the implied warranty of
1641       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See either the
1642       GNU General Public License or the Artistic License for more details.
1643
1644       You should have received a copy of the Artistic License with this
1645       module, in the file ARTISTIC.  If not, I'll be glad to provide one.
1646
1647       You should have received a copy of the GNU General Public License along
1648       with this program; if not, write to the Free Software Foundation, Inc.,
1649       59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
1650
1651
1652
1653perl v5.30.1                      2020-01-29               CGI::Application(3)
Impressum