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

NAME

6       CGI::Ex::App - Anti-framework application framework.
7

VERSION

9       version 2.50
10

SYNOPSIS

12       A basic example:
13
14           -------- File: /cgi-bin/my_cgi --------
15
16           #!/usr/bin/perl -w
17
18           use strict;
19           use base qw(CGI::Ex::App);
20
21           __PACKAGE__->navigate;
22           exit;
23
24           sub main_file_print {
25               return \ "Hello World!";
26           }
27
28       Properly put content in an external file...
29
30           -------- File: /cgi-bin/my_cgi --------
31
32           #!/usr/bin/perl -w
33
34           use strict;
35           use base qw(CGI::Ex::App);
36
37           __PACKAGE__->navigate;
38
39           sub template_path { '/var/www/templates' }
40
41
42           -------- File: /var/www/templates/my_cgi/main.html --------
43
44           Hello World!
45
46       Adding substitutions...
47
48           -------- File: /cgi-bin/my_cgi --------
49
50           #!/usr/bin/perl -w
51
52           use strict;
53           use base qw(CGI::Ex::App);
54
55           __PACKAGE__->navigate;
56
57           sub template_path { '/var/www/templates' }
58
59           sub main_hash_swap {
60               my $self = shift;
61               return {
62                   greeting => 'Hello',
63                   date     => sub { scalar localtime },
64               };
65           }
66
67
68           -------- File: /var/www/templates/my_cgi/main.html --------
69
70           [% greeting %] World! ([% date %])
71
72       Add forms and  validation (inluding javascript validation)...
73
74           -------- File: /cgi-bin/my_cgi --------
75
76           #!/usr/bin/perl -w
77
78           use strict;
79           use base qw(CGI::Ex::App);
80
81           __PACKAGE__->navigate;
82
83           sub template_path { '/var/www/templates' }
84
85           sub main_hash_swap { {date => sub { scalar localtime }} }
86
87           sub main_hash_fill {
88               return {
89                   guess => 50,
90               };
91           }
92
93           sub main_hash_validation {
94               return {
95                   guess => {
96                       required => 1,
97                       compare1       => '<= 100',
98                       compare1_error => 'Please enter a value less than 101',
99                       compare2       => '>  0',
100                       compare2_error => 'Please enter a value greater than 0',
101                   },
102               };
103           }
104
105           sub main_finalize {
106               my $self   = shift;
107               my $form   = $self->form;
108
109               $self->add_to_form({was_correct => ($form->{'guess'} == 23)});
110
111               return 0; # indicate to show the page without trying to move along
112           }
113
114
115           -------- File: /var/www/templates/my_cgi/main.html --------
116
117           <h2>Hello World! ([% date %])</h2>
118
119           [% IF was_correct %]
120              <b>Correct!</b> - The number was [% guess %].<br>
121           [% ELSIF guess %]
122              <b>Incorrect</b> - The number was not [% guess %].<br>
123           [% END %]
124
125           <form name="[% form_name %]" method="post">
126
127           Enter a number between 1 and 100: <input type="text" name="guess"><br>
128           <span id="guess_error" style="color:red">[% guess_error %]</span><br>
129
130           <input type="submit">
131           </form>
132
133           [% js_validation %]
134
135       There are infinite possibilities.  There is a longer "SYNOPSIS" after
136       the process flow discussion and more examples near the end of this
137       document.  It is interesting to note that there have been no databases
138       so far.  It is very, very difficult to find a single database
139       abstraction that fits every model.  CGI::Ex::App is Controller/Viewer
140       that is somewhat Model agnostic and doesn't come with any default
141       database abstraction.
142

DESCRIPTION

144       Fill in the blanks and get a ready made web application.
145
146       This module is somewhat similar in spirit to CGI::Application,
147       CGI::Path, and CGI::Builder and any other "CGI framework."  As with the
148       others, CGI::Ex::App tries to do as much of the mundane things, in a
149       simple manner, without getting in the developer's way.  However, there
150       are various design patterns for CGI applications that CGI::Ex::App
151       handles for you that the other frameworks require you to bring in extra
152       support.  The entire CGI::Ex suite has been taylored to work seamlessly
153       together.  Your mileage in building applications may vary.
154
155       If you build applications that submit user information, validate it,
156       re-display it, fill in forms, or separate logic into separate modules,
157       then this module may be for you.  If all you need is a dispatch engine,
158       then this still may be for you.  If all you want is to look at user
159       passed information, then this may still be for you.  If you like
160       writing bare metal code, this could still be for you.  If you don't
161       want to write any code, this module will help - but you still need to
162       provide your key actions and html.
163
164       One of the great benefits of CGI::Ex::App vs. Catalyst or Rails style
165       frameworks is that the model of CGI::Ex::App can be much more abstract.
166       And models often are abstract.
167

DEFAULT PROCESS FLOW

169       The following pseudo-code describes the process flow of the
170       CGI::Ex::App framework.  Several portions of the flow are encapsulated
171       in hooks which may be completely overridden to give different flow.
172       All of the default actions are shown.  It may look like a lot to
173       follow, but if the process is broken down into the discrete operations
174       of step iteration, data validation, and template printing the flow
175       feels more natural.
176
177   navigate
178       The process starts off by calling ->navigate.
179
180           navigate {
181               eval {
182                   ->pre_navigate
183                   ->nav_loop
184                   ->post_navigate
185               }
186               # dying errors will run the ->handle_error method
187
188               ->destroy
189           }
190
191   nav_loop
192       The nav_loop method will run as follows:
193
194           nav_loop {
195               ->path (get the array of path steps)
196                   # ->path_info_map_base (method - map ENV PATH_INFO to form)
197                   # look in ->form for ->step_key
198                   # make sure step is in ->valid_steps (if defined)
199
200               ->pre_loop($path)
201                   # navigation stops if true
202
203               foreach step of path {
204
205                   ->require_auth (hook)
206                       # exits nav_loop if true
207
208                   ->morph (hook)
209                       # check ->allow_morph (hook)
210                       # ->morph_package (hook - get the package to bless into)
211                       # ->fixup_after_morph if morph_package exists
212                       # if no package is found, process continues in current file
213
214                   ->path_info_map (hook - map PATH_INFO to form)
215
216                   ->run_step (hook)
217
218                   ->refine_path (hook)
219                       # only called if run_step returned false (page not printed)
220                       ->next_step (hook) # find next step and add to path
221                       ->set_ready_validate(0) (hook)
222
223                   ->unmorph (hook)
224                       # ->fixup_before_unmorph if blessed to current package
225
226                   # exit loop if ->run_step returned true (page printed)
227
228               } end of foreach step
229
230               ->post_loop
231                   # navigation stops if true
232
233               ->default_step
234               ->insert_path (puts the default step into the path)
235               ->nav_loop (called again recursively)
236
237           } end of nav_loop
238
239   run_step (hook)
240       For each step of the path the following methods will be run during the
241       run_step hook.
242
243           run_step {
244               ->pre_step (hook)
245                   # skips this step if true and exit nav_loop
246
247               ->skip (hook)
248                   # skips this step if true and stays in nav_loop
249
250               ->prepare (hook - defaults to true)
251
252               ->info_complete (hook - ran if prepare was true)
253                   ->ready_validate (hook)
254                       ->validate_when_data (hook)
255                       # returns false from info_complete if ! ready_validate
256                   ->validate (hook - uses CGI::Ex::Validate to validate form info)
257                       ->hash_validation (hook)
258                          ->file_val (hook)
259                              ->vob_path (defaults to template_path)
260                              ->base_dir_rel
261                              ->name_module
262                              ->name_step
263                              ->ext_val
264                   # returns true if validate is true or if nothing to validate
265
266               ->finalize (hook - defaults to true - ran if prepare and info_complete were true)
267
268               if ! ->prepare || ! ->info_complete || ! ->finalize {
269                   ->prepared_print
270                       ->hash_base (hook)
271                       ->hash_common (hook)
272                       ->hash_form (hook)
273                       ->hash_fill (hook)
274                       ->hash_swap (hook)
275                       ->hash_errors (hook)
276                       # merge form, base, common, and fill into merged fill
277                       # merge form, base, common, swap, and errors into merged swap
278                       ->print (hook - passed current step, merged swap hash, and merged fill)
279                            ->file_print (hook - uses base_dir_rel, name_module, name_step, ext_print)
280                            ->swap_template (hook - processes the file with Template::Alloy)
281                                 ->template_args (hook - passed to Template::Alloy->new)
282                            ->fill_template (hook - fills the any forms with CGI::Ex::Fill)
283                                 ->fill_args (hook - passed to CGI::Ex::Fill::fill)
284                            ->print_out (hook - print headers and the content to STDOUT)
285
286                   ->post_print (hook - used for anything after the print process)
287
288                   # return true to exit from nav_loop
289               }
290
291               ->post_step (hook)
292                   # exits nav_loop if true
293
294           } end of run_step
295
296       It is important to learn the function and placement of each of the
297       hooks in the process flow in order to make the most of CGI::Ex::App.
298       It is enough to begin by learning a few common hooks - such as
299       hash_validation, hash_swap, and finalize, and then learn about other
300       hooks as needs arise.  Sometimes, it is enough to simply override the
301       run_step hook and take care of processing the entire step yourself.
302
303       Because of the hook based system, and because CGI::Ex::App uses
304       sensible defaults, it is very easy to override a little or a lot which
305       ends up giving the developer a lot of flexibility.
306
307       Additionally, it should be possible to use CGI::Ex::App with the other
308       frameworks such as CGI::Application or CGI::Prototype.  For these you
309       could simple let each "runmode" call the run_step hook of CGI::Ex::App
310       and you will instantly get all of the common process flow for free.
311

MAPPING URI TO STEP

313       The default out of the box configuration will map URIs to steps as
314       follows:
315
316           # Assuming /cgi-bin/my_app is the program being run
317
318          URI:  /cgi-bin/my_app
319           STEP: main
320           FORM: {}
321           WHY:  No other information is passed.  The path method is
322                 called which eventually calls ->default_step which
323                 defaults to "main"
324
325          URI:  /cgi-bin/my_app?foo=bar
326           STEP: main
327           FORM: {foo => "bar"}
328           WHY:  Same as previous example except that QUERY_STRING
329                 information was passed and placed in form.
330
331          URI:  /cgi-bin/my_app?step=my_step
332           STEP: my_step
333           FORM: {step => "my_step"}
334           WHY:  The path method is called which looks in $self->form
335                 for the key ->step_key (which defaults to "step").
336
337          URI:  /cgi-bin/my_app?step=my_step&foo=bar
338           STEP: my_step
339           FORM: {foo => "bar", step => "my_step"}
340           WHY:  Same as before but another parameter was passed.
341
342          URI:  /cgi-bin/my_app/my_step
343           STEP: my_step
344           FORM: {step => "my_step"}
345           WHY:  The path method is called which called path_info_map_base
346                 which matched $ENV{'PATH_INFO'} using the default regex
347                 of qr{^/(\w+)$} and place the result in
348                 $self->form->{$self->step_key}.  Path then looks in
349                 $self->form->{$self->step_key} for the initial step. See
350                 the path_info_map_base method for more information.
351
352          URI:  /cgi-bin/my_app/my_step?foo=bar
353           STEP: my_step
354           FORM: {foo => "bar", step => "my_step"}
355           WHY:  Same as before but other parameters were passed.
356
357          URI:  /cgi-bin/my_app/my_step?step=other_step
358           STEP: other_step
359           FORM: {step => "other_step"}
360           WHY:  The same procedure took place, but when the PATH_INFO
361                 string was matched, the form key "step" already existed
362                 and was not replaced by the value from PATH_INFO.
363
364       The remaining examples in this section are based on the assumption that
365       the following method is installed in your script.
366
367           sub my_step_path_info_map {
368               return [
369                   [qr{^/\w+/(\w+)/(\d+)$}, 'foo', 'id'],
370                   [qr{^/\w+/(\w+)$}, 'foo'],
371                   [qr{^/\w+/(.+)$}, 'anything_else'],
372               ];
373           }
374
375          URI:  /cgi-bin/my_app/my_step/bar
376           STEP: my_step
377           FORM: {foo => "bar"}
378           WHY:  The step was matched as in previous examples using
379                 path_info_map_base.  However, the form key "foo"
380                 was set to "bar" because the second regex returned
381                 by the path_info_map hook matched the PATH_INFO string
382                 and the corresponding matched value was placed into
383                 the form using the keys specified following the regex.
384
385          URI:  /cgi-bin/my_app/my_step/bar/1234
386           STEP: my_step
387           FORM: {foo => "bar", id => "1234"}
388           WHY:  Same as the previous example, except that the first
389                 regex matched the string.  The first regex had two
390                 match groups and two form keys specified.  Note that
391                 it is important to order your match regexes in the
392                 order that will match the most data.  The third regex
393                 would also match this PATH_INFO.
394
395          URI:  /cgi-bin/my_app/my_step/some/other/type/of/data
396           STEP: my_step
397           FORM: {anything_else => 'some/other/type/of/data'}
398           WHY:  Same as the previous example, except that the third
399                 regex matched.
400
401          URI:  /cgi-bin/my_app/my_step/bar?bling=blang
402           STEP: my_step
403           FORM: {foo => "bar", bling => "blang"}
404           WHY:  Same as the first sample, but additional QUERY_STRING
405                 information was passed.
406
407          URI:  /cgi-bin/my_app/my_step/one%20two?bar=three%20four
408           STEP: my_step
409           FORM: {anything_else => "one two", bar => "three four"}
410           WHY:  The third path_info_map regex matched.  Note that the
411                 %20 in bar was unescaped by CGI::param, but the %20
412                 in anything_else was unescaped by Apache.  If you are
413                 not using Apache, this behavior may vary.  CGI::Ex::App
414                 doesn't decode parameters mapped from PATH_INFO.
415
416       See the path method for more information about finding the initial step
417       of the path.
418
419       The form method calls CGI::Ex::form which uses CGI::param to retrieve
420       GET and POST parameters.  See the form method for more information on
421       how GET and POST parameters are parsed.
422
423       See the path_info_map_base method, and path_info_map hook for more
424       information on how the path_info maps function.
425
426       Using the following code is very useful for determing what hooks have
427       taken place:
428
429          use CGI::Ex::Dump qw(debug);
430
431          sub post_navigate {
432              my $self = shift;
433              debug $self->dump_history, $self->form;
434          }
435

ADDING DATA VALIDATION TO A STEP

437       CGI::Ex::App uses CGI::Ex::Validate for its data validation.  See
438       CGI::Ex::Validate for more information about the many ways you can
439       validate your data.
440
441       The default hash_validation hook returns an empty hashref.  This means
442       that passed in data is all valid and the script will automatically call
443       the step's finalize method.
444
445       The following shows how to add some contrived validation to a step
446       called "my_step".
447
448           sub my_step_hash_validation {
449               return {
450                   username => {
451                       required    => 1,
452                       match       => 'm/^(\w+)$/',
453                       match_error => 'The $field field may only contain word characters',
454                       max_len     => 20,
455                   },
456                   password => {
457                       required => 1,
458                       max_len  => 15,
459                   },
460                   password_verify => {
461                       validate_if => 'password',
462                       equals      => 'password',
463                   },
464                   usertype => {
465                       required => 1,
466                       enum     => [qw(animal vegetable mineral)],
467                   },
468               };
469           }
470
471       The step will continue to display the html form until all of the fields
472       pass validation.
473
474       See the hash_validation hook and validate hook for more information
475       about how this takes place.
476

ADDING JAVASCRIPT DATA VALIDATION TO A STEP

478       You must first provide a hash_validation hook as explained in the
479       previous section.
480
481       Once you have a hash_validation hook, you would place the following
482       tags into your HTML template.
483
484           <form name="[% form_name %]" method="post">
485           ...
486           </form>
487           [% js_validation %]
488
489       The "form_name" swap-in places a name on the form that the javascript
490       returned by the js_validation swap-in will be able to find and check
491       for validity.
492
493       See the hash_validation, js_validation, and form_name hooks for more
494       information.
495
496       Also, CGI::Ex::validate.js allows for inline errors in addition to or
497       in replacement of an alert message.  To use inline errors, you must
498       provide an element in your HTML document where this inline message can
499       be placed.  The common way to do it is as follows:
500
501           <input type="text" name="username"><br>
502           <span class="error" id="username_error">[% username_error %]</span>
503
504       The span around the error allows for the error css class and it
505       provides a location that the Javascript validation can populate with
506       errors.  The [% username_error %] provides a location for errors
507       generated on the server side to be swapped in.  If there was no error
508       the [% username_error %] tag would default to "".
509

ADDING ADDITIONAL TEMPLATE VARIABLES

511       All variables returned by the hash_base, hash_common, hash_form,
512       hash_swap, and hash_errors hooks are available for swapping in
513       templates.
514
515       The following shows how to add variables using the hash_swap hook on
516       the step "main".
517
518           sub main_hash_swap {
519               return {
520                   color   => 'red',
521                   choices => [qw(one two three)],
522                   "warn"  => sub { warn @_ },
523               };
524           }
525
526       You could also return the fields from the hash_common hook and they
527       would be available in both the template swapping as well as form
528       filling.
529
530       See the hash_base, hash_common, hash_form, hash_swap, hash_errors,
531       swap_template, and template_args hooks for more information.
532
533       The default template engine used is Template::Alloy.  The default
534       interface used is TT which is the Template::Toolkit interface.
535       Template::Alloy allows for using TT documents, HTML::Template
536       documents, HTML::Template::Expr documents, Text::Tmpl documents, or
537       Velocity (VTL) documents.  See the Template::Alloy documentation for
538       more information.
539

ADDING ADDITIONAL FORM FILL VARIABLES

541       All variables returned by the hash_base, hash_common, hash_form, and
542       hash_fill hooks are available for filling html fields in on templates.
543
544       The following shows how to add variables using the hash_fill hook on
545       the step "main".
546
547           sub main_hash_fill {
548               return {
549                   color   => 'red',
550                   choices => [qw(one two three)],
551               };
552           }
553
554       You could also return the fields from the hash_common hook and they
555       would be available in both the form filling as well as in the template
556       swapping.
557
558       See the hash_base, hash_common, hash_form, hash_swap, hash_errors,
559       fill_template, and fill_args hooks for more information.
560
561       The default form filler is CGI::Ex::Fill which is similar to
562       HTML::FillInForm but has several benefits.  See the CGI::Ex::Fill
563       module for the available options.
564

FINDING TEMPLATES AND VALIDATION FILES

566       CGI::Ex::App tries to help your applications use a good template
567       directory layout, but allows for you to override everything.
568
569       External template files are used for storing your html templates and
570       for storing your validation files (if you use externally stored
571       validation files).
572
573       The default file_print hook will look for content on your file system,
574       but it can also be completely overridden to return a reference to a
575       scalar containing the contents of your file (beginning with version
576       2.14 string references can be cached which makes templates passed this
577       way "first class" citizens).  Actually it can return anything that
578       Template::Alloy (Template::Toolkit compatible) will treat as input.
579       This templated html is displayed to the user during any step that
580       enters the "print" phase.
581
582       Similarly the default file_val hook will look for a validation file on
583       the file system, but it too can return a reference to a scalar
584       containing the contents of a validation file.  It may actually return
585       anything that the CGI::Ex::Validate get_validation method is able to
586       understand.  This validation is used by the default "info_complete"
587       method for verifying if the submitted information passes its specific
588       checks.  A more common way of inlining validation is to return a
589       validation hash from a hash_validation hook override.
590
591       If the default file_print and file_val hooks are used, the following
592       methods are employed for finding templates and validation files on your
593       filesystem (they are also documented more in the HOOKS AND METHODS
594       section.
595
596       template_path
597           Absolute path or arrayref of paths to the base templates directory.
598           Defaults to base_dir_abs which defaults to ['.'].
599
600       base_dir_rel
601           Relative path inside of the template_path directory where content
602           can be found.  Default "".
603
604       name_module
605           Directory inside of base_dir_rel where files for the current CGI
606           (module) will be stored.  Default value is $ENV{SCRIPT_NAME} with
607           path and extension removed.
608
609       name_step
610           Used with ext_print and ext_val for creating the filename that will
611           be looked for inside of the name_module directory.  Default value
612           is the current step.
613
614       ext_print and ext_val
615           Filename extensions added to name_step to create the filename
616           looked for inside of the name_module directory.  Default is "html"
617           for ext_print and "val" for ext_val.
618
619       It may be easier to understand the usage of each of these methods by
620       showing a contrived example.  The following is a hypothetical layout
621       for your templates:
622
623           /home/user/templates/
624           /home/user/templates/chunks/
625           /home/user/templates/wrappers/
626           /home/user/templates/content/
627           /home/user/templates/content/my_app/
628           /home/user/templates/content/my_app/main.html
629           /home/user/templates/content/my_app/step1.html
630           /home/user/templates/content/my_app/step1.val
631           /home/user/templates/content/another_cgi/main.html
632
633       In this example we would most likely set values as follows:
634
635           template_path /home/user/templates
636           base_dir_rel  content
637           name_module   my_app
638
639       The name_module method defaults to the name of the running program, but
640       with the path and extension removed.  So if we were running
641       /cgi-bin/my_app.pl, /cgi-bin/my_app, or /anypath/my_app, then
642       name_module would default to "my_app" and we wouldn't have to hard code
643       the value.  Often it is wise to set the value anyway so that we can
644       change the name of the cgi script without effecting where template
645       content should be stored.
646
647       Continuing with the example and assuming that name of the step that the
648       user has requested is "step1" then the following values would be
649       returned:
650
651           template_path /home/user/templates
652           base_dir_rel  content
653           name_module   my_app
654           name_step     step1
655           ext_print     html
656           ext_val       val
657
658           file_print    content/my_app/step1.html
659           file_val      /home/user/templates/content/my_app/step1.val
660
661       The call to the template engine would look something like the
662       following:
663
664           my $t = $self->template_obj({
665               INCLUDE_PATH => $self->template_path, # defaults to base_dir_abs
666           });
667
668           $t->process($self->file_print($step), \%vars);
669
670       The template engine would then look for the relative file inside of the
671       absolute paths (from template_path).
672
673       The call to the validation engine would pass the absolute filename that
674       is returned by file_val.
675
676       The name_module and name_step methods can return filenames with
677       additional directories included.  The previous example could also have
678       been setup using the following values:
679
680           template_path /home/user/templates
681           base_dir_rel
682           name_module   content/my_app
683
684       In this case the same values would be returned for the file_print and
685       file_val hooks as were returned in the previous setup.
686

SYNOPSIS (A LONG "SYNOPSIS")

688       This example script would most likely be in the form of a cgi,
689       accessible via the path http://yourhost.com/cgi-bin/my_app (or however
690       you do CGIs on your system.  About the best way to get started is to
691       paste the following code into a cgi script (such as cgi-bin/my_app) and
692       try it out.  A detailed walk-through follows in the next section.
693       There is also a longer recipe database example at the end of this
694       document that covers other topics including making your module a
695       mod_perl handler.
696
697           ### File: /var/www/cgi-bin/my_app (depending upon Apache configuration)
698           ### --------------------------------------------
699           #!/usr/bin/perl -w
700
701           use strict;
702           use base qw(CGI::Ex::App);
703           use CGI::Ex::Dump qw(debug);
704
705           __PACKAGE__->navigate;
706           # OR
707           # my $obj = __PACKAGE__->new;
708           # $obj->navigate;
709
710           exit;
711
712           ###------------------------------------------###
713
714           sub post_navigate {
715               # show what happened
716               debug shift->dump_history;
717           }
718
719           sub main_hash_validation {
720               return {
721                   'general no_alert'   => 1,
722                   'general no_confirm' => 1,
723                   'group order' => [qw(username password password2)],
724                   username => {
725                       required => 1,
726                       min_len  =>  3,
727                       max_len  => 30,
728                       match    => 'm/^\w+$/',
729                       match_error => 'You may only use letters and numbers.',
730                   },
731                   password => {
732                       required => 1,
733                       min_len  => 6,
734                   },
735                   password2 => {
736                       equals => 'password',
737                   },
738               };
739           }
740
741           sub main_file_print {
742               # reference to string means ref to content
743               # non-reference means filename
744               return \ "<h1>Main Step</h1>
745                 <form method=post name=[% form_name %]>
746                 <input type=hidden name=step>
747                 <table>
748                 <tr>
749                   <td><b>Username:</b></td>
750                   <td><input type=text name=username><span style='color:red' id=username_error>[% username_error %]</span></td>
751                 </tr><tr>
752                   <td><b>Password:</b></td>
753                   <td><input type=text name=password><span style='color:red' id=password_error>[% password_error %]</span></td>
754                 </tr><tr>
755                   <td><b>Verify Password:</b></td>
756                   <td><input type=text name=password2><span style='color:red' id=password2_error>[% password2_error %]</span></td>
757                 </tr>
758                 <tr><td colspan=2 align=right><input type=submit></td></tr>
759                 </table>
760                 </form>
761                 [% js_validation %]
762               ";
763           }
764
765           sub main_finalize {
766               my $self = shift;
767
768               if ($self->form->{'username'} eq 'bar') {
769                   $self->add_errors(username => 'A trivial check to say the username cannot be "bar"');
770                   return 0;
771               }
772
773               debug $self->form, "Do something useful with form here in the finalize hook.";
774
775               ### add success step
776               $self->add_to_swap({success_msg => "We did something"});
777               $self->append_path('success');
778               $self->set_ready_validate(0);
779               return 1;
780           }
781
782           sub success_file_print {
783               \ "<div style=background:lightblue>
784                  <h1>Success Step - [% success_msg %]</h1>
785                  Username: <b>[% username %]</b><br>
786                  Password: <b>[% password %]</b><br>
787                  </div>
788                 ";
789           }
790
791           __END__
792
793       Note: This example would be considerably shorter if the html file
794       (file_print) and the validation file (file_val) had been placed in
795       separate files.  Though CGI::Ex::App will work "out of the box" as
796       shown it is more probable that any platform using it will customize the
797       various hooks to their own tastes (for example, switching print to use
798       a templating system other than Template::Alloy).
799

SYNOPSIS STEP BY STEP

801       This section goes step by step over the previous example.
802
803       Well - we start out with the customary CGI introduction.
804
805           #!/usr/bin/perl -w
806
807           use strict;
808           use base qw(CGI::Ex::App);
809           use CGI::Ex::Dump qw(debug);
810
811       Note:  the "use base" is not normally used in the "main" portion of a
812       script.  It does allow us to just do __PACKAGE__->navigate.
813
814       Now we need to invoke the process:
815
816           __PACKAGE__->navigate;
817           # OR
818           # my $obj = __PACKAGE__->new;
819           # $obj->navigate;
820           exit;
821
822       Note: the "exit" isn't necessary - but it is kind of nice to infer that
823       process flow doesn't go beyond the ->navigate call.
824
825       The navigate routine is now going to try and "run" through a series of
826       steps.  Navigate will call the ->path method which should return an
827       arrayref containing the valid steps.  By default, if path method has
828       not been overridden, the path method will default first to the step
829       found in form key named ->step_name, then it will fall to the contents
830       of $ENV{'PATH_INFO'}.  If navigation runs out of steps to run it will
831       run the step found in ->default_step which defaults to 'main'.  So the
832       URI '/cgi-bin/my_app' would run the step 'main' first by default.  The
833       URI '/cgi-bin/my_app?step=foo' would run the step 'foo' first.  The URI
834       '/cgi-bin/my_app/bar' would run the step 'bar' first.
835
836       CGI::Ex::App allows for running steps in a preset path or each step may
837       choose the next step that should follow.  The navigate method will go
838       through one step of the path at a time and see if it is completed
839       (various methods determine the definition of "completed").  This preset
840       type of path can also be automated using the CGI::Path module.  Rather
841       than using a preset path, CGI::Ex::App also has methods that allow for
842       dynamic changing of the path, so that each step can determine which
843       step to do next (see the goto_step, append_path, insert_path, and
844       replace_path methods).
845
846       During development it would be nice to see what happened during the
847       course of our navigation.  This is stored in the arrayref contained in
848       ->history.  There is a method that is called after all of the
849       navigation has taken place called "post_navigate".  This chunk will
850       display history after we have printed the content.
851
852           sub post_navigate {
853               debug shift->dump_history;
854           } # show what happened
855
856       Ok.  Finally we are looking at the methods used by each step of the
857       path.  The hook mechanism of CGI::Ex::App will look first for a method
858       ${step}_${hook_name} called before falling back to the method named
859       $hook_name.  Internally in the code there is a call that looks like
860       $self->run_hook('hash_validation', $step).  In this case the step is
861       main.  The dispatch mechanism finds our method at the following chunk
862       of code.
863
864           sub main_hash_validation { ... }
865
866       The process flow will see if the data is ready to validate.  Once it is
867       ready (usually when the user presses the submit button) the data will
868       be validated.  The hash_validation hook is intended to describe the
869       data and will be tested using CGI::Ex::Validate.  See the
870       CGI::Ex::Validate perldoc for more information about the many types of
871       validation available.
872
873           sub main_file_print { ... }
874
875       The navigation process will see if user submitted information (the
876       form) is ready for validation.  If not, or if validation fails, the
877       step needs to be printed.  Eventually the file_print hook is called.
878       This hook should return either the filename of the template to be
879       printed, or a reference to the actual template content.  In this
880       example we return a reference to the content to be printed (this is
881       useful for prototyping applications and is also fine in real world use
882       - but generally production applications use external html templates).
883
884       A few things to note about the template:
885
886       First, we add a hidden form field called step.  This will be filled in
887       automatically at a later point with the current step we are on.
888
889       We provide locations to swap in inline errors.
890
891           <span style="color:red" id="username_error">[% username_error %]</span>
892
893       As part of the error html we name each span with the name of the error.
894       This will allow for us to have Javascript update the error spots when
895       the javascript finds an error.
896
897       At the very end we add the TT variable [% js_validation %].  This swap
898       in is provided by the default hash_base hook and will provide for form
899       data to be validated using javascript.
900
901       Once the process flow has deemed that the data is validated, it then
902       calls the finalize hook.  Finalize is where the bulk of operations
903       should go.  We'll look at it more in depth.
904
905           sub main_finalize {
906               my $self = shift;
907               my $form = $self->form;
908
909       At this point, all of the validated data is in the $form hashref.
910
911               if ($form->{'username'} eq 'bar') {
912                   $self->add_errors(username => 'A trivial check to say the username cannot be "bar"');
913                   return 0;
914               }
915
916       It is most likely that though the data is of the correct type and
917       formatting, it still isn't completely correct.  This previous section
918       shows a hard coded test to see if the username was 'bar'.  If it was
919       then an appropriate error will be set, the routine returns 0 and the
920       run_step process knows that it needs to redisplay the form page for
921       this step.  The username_error will be shown inline.  The program could
922       do more complex things such as checking to see if the username was
923       already taken in a database.
924
925               debug $form, "Do something useful with form here in the finalize hook.";
926
927       This debug $form piece is simply a place holder.  It is here that the
928       program would do something useful such as add the information to a
929       database.
930
931               ### add success step
932               $self->add_to_swap({success_msg => "We did something"});
933
934       Now that we have finished finalize, we add a message that will be
935       passed to the template engine.
936
937               $self->append_path('success');
938               $self->set_ready_validate(0);
939
940       The program now needs to move on to the next step.  In this case we
941       want to follow with a page that informs us we succeeded.  So, we append
942       a step named "success".  We also call set_ready_validate(0) to inform
943       the navigation control that the form is no longer ready to validate -
944       which will cause the success page to print without trying to validate
945       the data.  It is normally a good idea to set this as leaving the engine
946       in a "ready to validate" state can result in an recursive loop (that
947       will be caught).
948
949               return 1;
950           }
951
952       We then return 1 which tells the engine that we completed this step
953       successfully and it needs to move on to the next step.
954
955       Finally we run the "success" step because we told it to.  That step
956       isn't ready to validate so it prints out the template page.
957
958       For more of a real world example, it would be good to read the sample
959       recipe db application included at the end of this document.
960

AVAILABLE METHODS / HOOKS

962       CGI::Ex::App's dispatch system works on the principles of hooks (which
963       are essentially glorified method lookups).  When the run_hook method is
964       called, CGI::Ex::App will look for a corresponding method call for that
965       hook for the current step name.  It is perhaps easier to show than to
966       explain.
967
968       If we are calling the "print" hook for the step "edit" we would call
969       run_hook like this:
970
971           $self->run_hook('print', 'edit', $template, \%swap, \%fill);
972
973       This would first look for a method named "edit_print".  If it is unable
974       to find a method by that name, it will look for a method named "print".
975       If it is unable to find this method - it will die.
976
977       If allow_morph is set to true, the same methods are searched for but it
978       becomes possible to move some of those methods into an external
979       package.
980
981       See the discussions under the methods named "find_hook" and "run_hook"
982       for more details.
983
984       Some hooks expect "magic" values to be replaced.  Often they are
985       intuitive, but sometimes it is easy to forget.  For example, the
986       finalize hook should return true (default) to indicate the step is
987       complete and false to indicate that it failed and the page should be
988       redisplayed.  You can import a set of constants that allows for human
989       readible names.
990
991           use CGI::Ex::App qw(:App__finalize);
992           OR
993           use MyAppPkg qw(:App__finalize); # if it is a subclass of CGI::Ex::App
994
995       This would import the following constants:
996       App__finalize__failed_and_show_page (0),
997       App__finalize__finished_and_move_to_next_step => (1 - default), and
998       App__finalize__finished_but_show_page ("" - still false).  These
999       constants are provided by CGI::Ex::App::Constants which also contains
1000       more options for usage.
1001
1002       The following is the alphabetical list of methods and hooks.
1003
1004       allow_morph (hook)
1005           Should return true if this step is allowed to "morph" the current
1006           App object into another package.  Default is false.  It is passed a
1007           single argument of the current step.  For more granularity, if true
1008           value is a hash, the step being morphed to must be in the hash.
1009
1010           If the returned value is "1", and the module doesn't exist, then
1011           the App will continue to run blessed into the current package.  If
1012           there is an error requiring the module or if the module doesn't
1013           exist and the return value is "2" (true but not 1), then App will
1014           die with the appropriate error.
1015
1016           To enable morphing for all steps, add the following: (Packages that
1017           don't exists won't be morphed to)
1018
1019               sub allow_morph { 1 }
1020
1021           To force morphing for all steps add the following:
1022
1023               sub allow_morph { 2 }
1024
1025           To enable morph on specific steps, do either of the following:
1026
1027               sub allow_morph {
1028                   return {
1029                       edit => 1,
1030                       delete => 2, # must morph
1031                   };
1032               }
1033
1034               # OR
1035
1036               sub allow_morph {
1037                   my ($self, $step) = @_;
1038                   return 1 if $step eq 'edit';
1039                   return 2 if $step eq 'delete';
1040                   return;
1041               }
1042
1043           See the morph "hook" for more information.
1044
1045       append_path (method)
1046           Arguments are the steps to append.  Can be called any time.  Adds
1047           more steps to the end of the current path.
1048
1049       auth_args (method)
1050           Should return a hashref that will be passed to the auth_obj method
1051           which should return a CGI::Ex::Auth compatible object.  It is
1052           augmented with arguments that integrate it into CGI::Ex::App.
1053
1054           See the get_valid_auth method and the CGI::Ex::Auth documentation.
1055
1056               sub auth_args {
1057                   return {
1058                       login_header => '<h1>My login header</h1>',
1059                       login_footer => '[% TRY %][% INCLUDE login/login_footer.htm %][% CATCH %]<!-- [% error %] -->[% END %]',
1060                       secure_hash_keys => [qw(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccc 2222222222222)],
1061                       # use_blowfish => 'my_blowfish_key',
1062                   };
1063               }
1064
1065       auth_data (method)
1066           Contains authentication data stored during the get_valid_auth
1067           method.  The data is normally blessed into the CGI::Ex::Auth::Data
1068           package which evaluates to false if there was an error and true if
1069           the authentication was successful - so this data can be defined but
1070           false.
1071
1072           See the get_valid_auth method.
1073
1074       auth_obj (method)
1075           Passed auth_args.  Should return a CGI::Ex::Auth compatible object.
1076           Default is to call CGI::Ex::Auth->new with the passed args.
1077
1078       base_dir_abs (method)
1079           Used as the absolute base directory to find template, validation
1080           and conf files.  It may return a single value or an arrayref of
1081           values, or a coderef that returns an arrayref or coderef of values.
1082           You may pass base_dir_abs as a parameter in the arguments passed to
1083           the "new" method.
1084
1085           Default value is ['.'].
1086
1087           For example, to pass multiple paths, you would use something
1088           similar to the following:
1089
1090               sub base_dir_abs {
1091                   return ['/my/path/one', '/some/other/path'];
1092               }
1093
1094           The base_dir_abs value is used by template_path along with the
1095           base_dir_rel, name_module, name_step, ext_print and ext_values for
1096           determining the values returned by the default file_print and
1097           file_val hooks.  See those methods for further discussion.
1098
1099           See the section on FINDING TEMPLATES for further discussion.
1100
1101           The base_dir_abs method is also used as the default value for
1102           conf_path and vob_path.
1103
1104       base_dir_rel (method)
1105           Added as a relative base directory to content under the
1106           base_dir_abs directory.
1107
1108           Default value is "".
1109
1110           The template_path method is used as top level where template
1111           includes may pull from, while the base_dir_rel is directory
1112           relative to the template_path where the content files will be
1113           stored.
1114
1115           A value for base_dir_rel may passed as a parameter in the arguments
1116           passed to the new method.
1117
1118           See the template_path and base_dir_abs methods for more discussion.
1119
1120           See the section on FINDING TEMPLATES for further discussion.
1121
1122       cleanup_user (method)
1123           Used as a hook during get_valid_auth.  Allows for cleaning up the
1124           username.  See the get_valid_auth method.
1125
1126               sub cleanup_user {
1127                   my ($self, $user) = @_;
1128                   return lc $user;
1129               }
1130
1131       clear_app (method)
1132           If the same CGI::Ex::App based object is used to run multiple
1133           navigate sessions, the clear_app method should be called which will
1134           attempt to clear as much session information as it can.  The
1135           following items will be cleared:
1136
1137               cgix
1138               vob
1139               form
1140               cookies
1141               stash
1142               path
1143               path_i
1144               history
1145               _morph_lineage_start_index
1146               _morph_lineage
1147               hash_errors
1148               hash_fill
1149               hash_swap
1150               hash_common
1151
1152       conf (method)
1153           Used by default in init_from_conf if load_conf returns true.  Will
1154           try to read the file returned by the conf_file method using the
1155           object returned by conf_obj using that object's read method.  If
1156           conf_validation returns a non-empty hashref, the conf hash will be
1157           validated using $self->vob->validate (see the validate method).
1158
1159           This method may be used for other purposes as well (including when
1160           load_conf is false)..
1161
1162           Caches results in $self->{'conf'}.
1163
1164           If the conf_file can't be found, the method will die unless
1165           conf_die_on_fail returns 0 (defaults to true).
1166
1167       conf_args
1168           Used by conf_obj.
1169
1170           Defaults to $self->{'conf_args'} which defaults to {}.  Will have
1171           paths => $self->conf_path added before passing to
1172           CGI::Ex::Conf->new.
1173
1174       conf_file (method)
1175           Used by conf for finding the configuration file to load.  Defaults
1176           to $self->{'conf_file'} which defaults $self->name_module with the
1177           extention returned by $self->ext_conf added on.  For example, if
1178           name_module returns "my_app" and ext_conf returns "ini" the value
1179           returned will be "my_app.ini".
1180
1181           The value returned can absolute.  If the value will be searched for
1182           in the paths passed to conf_obj.
1183
1184           The ext_conf may be any of those extentions understood by
1185           CGI::Ex::Conf.
1186
1187       conf_obj
1188           Used by the conf method to load the file returned by conf_file.
1189           Defaults to conf_obj which defaults to loading args from conf_args,
1190           adding in paths returned by conf_path, and calling
1191           CGI::Ex::Conf->new.
1192
1193           Any object that provides a read method that returns a hashref can
1194           be used.
1195
1196       conf_path
1197           Defaults to $self->{'conf_path'} which defaults to base_dir_abs.
1198           Should be a path or an arrayref of paths to look the configuration
1199           file returned by conf_file when that file is not absolute.
1200
1201       conf_validation
1202           Used by default conf method.  Defaults to an empty hashref.  If
1203           non-empty hashref is passed, the hashref returned by conf_obj->read
1204           will be validated using the hashref returned by conf_validation.
1205
1206       current_step (method)
1207           Returns the current step that the nav_loop is functioning on.
1208
1209       default_step (method)
1210           Step to show if the path runs out of steps.  Default value is the
1211           'default_step' property which defaults to 'main'.
1212
1213           If nav_loop runs of the end of the path (runs out of steps), this
1214           method is called, the step is added to the path, and nav_loop calls
1215           itself recursively.
1216
1217       destroy (method)
1218           Called at the end of navigate after all other actions have run.
1219           Can be used for undoing things done in the ->init method called
1220           during the ->new method.
1221
1222       dump_history (method)
1223           Show simplified trace information of which steps were called, the
1224           order they were called in, the time they took to run, and a brief
1225           list of the output (to see the full response returned by each hook,
1226           pass a true value as the only argument to dump_history -
1227           $self->dump_history(1)).  Indentation is also applied to show which
1228           hooks called other hooks.
1229
1230           The first line shows the amount of time elapsed for the entire
1231           navigate execution.  Subsequent lines contain:
1232
1233               Step   - the name of the current step.
1234               Hook   - the name of the hook being called.
1235               Found  - the name of the method that was found.
1236               Time   - the total elapsed seconds that method took to run.
1237               Output - the response of the hook - shown in shortened form.
1238
1239           Note - to get full output responses - pass a true value to
1240           dump_history - or just call ->history.  Times displayed are to 5
1241           decimal places - this accuracy can only be provided if the
1242           Time::HiRes module is installed on your system (it will only be
1243           used if installed).
1244
1245           It is usually best to print this history during the post_navigate
1246           method as in the following:
1247
1248               use CGI::Ex::Dump qw(debug);
1249               sub post_navigate { debug shift->dump_history }
1250
1251           The following is a sample output of dump_history called from the
1252           sample recipe application at the end of this document.  The step
1253           called is "view".
1254
1255               debug: admin/Recipe.pm line 14
1256               shift->dump_history = [
1257                       "Elapsed: 0.00562",
1258                       "view - require_auth - require_auth - 0.00001 - 0",
1259                       "view - run_step - run_step - 0.00488 - 1",
1260                       "    view - pre_step - pre_step - 0.00003 - 0",
1261                       "    view - skip - view_skip - 0.00004 - 0",
1262                       "    view - prepare - prepare - 0.00003 - 1",
1263                       "    view - info_complete - info_complete - 0.00010 - 0",
1264                       "        view - ready_validate - ready_validate - 0.00004 - 0",
1265                       "    view - prepared_print - prepared_print - 0.00441 - 1",
1266                       "        view - hash_base - hash_base - 0.00009 - HASH(0x84ea6ac)",
1267                       "        view - hash_common - view_hash_common - 0.00148 - HASH(0x8310a20)",
1268                       "        view - hash_form - hash_form - 0.00004 - HASH(0x84eaa78)",
1269                       "        view - hash_fill - hash_fill - 0.00003 - {}",
1270                       "        view - hash_swap - hash_swap - 0.00003 - {}",
1271                       "        view - hash_errors - hash_errors - 0.00003 - {}",
1272                       "        view - print - print - 0.00236 - 1",
1273                       "            view - file_print - file_print - 0.00024 - recipe/view.html",
1274                       "                view - name_module - name_module - 0.00007 - recipe",
1275                       "                view - name_step - name_step - 0.00004 - view",
1276                       "            view - swap_template - swap_template - 0.00161 - <html> ...",
1277                       "                view - template_args - template_args - 0.00008 - HASH(0x865abf8)",
1278                       "            view - fill_template - fill_template - 0.00018 - 1",
1279                       "                view - fill_args - fill_args - 0.00003 - {}",
1280                       "            view - print_out - print_out - 0.00015 - 1",
1281                       "    view - post_print - post_print - 0.00003 - 0"
1282               ];
1283
1284       error_step (method)
1285           Defaults to "__error".  The name of a step to run should a dying
1286           error be caught by the default handle_error method.  See the
1287           handle_error method.
1288
1289       exit_nav_loop (method)
1290           This method should not normally used but there is no problem with
1291           using it on a regular basis.  Essentially it is a "goto" that
1292           allows for a long jump to the end of all nav_loops (even if they
1293           are recursively nested).  This effectively short circuits all
1294           remaining hooks for the current and remaining steps.  It is used to
1295           allow the ->goto_step functionality.  If the application has
1296           morphed, it will be unmorphed before returning.  Also - the
1297           post_navigate method will still be called.
1298
1299       ext_conf
1300           Used by the default conf_file method.  Defaults to
1301           $self->{'ext_conf'} which defaults to 'pl' meaning that the read
1302           configuration file should return a valid perl hashref.
1303
1304       ext_print (method)
1305           Added as suffix to "name_step" during the default file_print hook.
1306
1307           Default value is 'html'.
1308
1309           For example, if name_step returns "foo" and ext_print returns
1310           "html" then the file "foo.html" will be searched for.
1311
1312           See the section on FINDING TEMPLATES for further discussion.
1313
1314       ext_val (method)
1315           Added as suffix to "name_step" during the default file_val hook.
1316
1317           Default value is 'val'.
1318
1319           For example, if name_step returns "foo" and ext_val returns "val"
1320           then the file "foo.val" will be searched for.
1321
1322           See the section on FINDING TEMPLATES for further discussion.
1323
1324       fill_args (hook)
1325           Returns a hashref of args that will be passed to the
1326           CGI::Ex::Fill::fill.  It is augmented with the template to swap and
1327           the fill hash.  This could be useful if you needed to only swap a
1328           particular form on the template page.  Arguments are passed
1329           directly to the fill function.
1330
1331              sub fill_args { {target => 'my_form'} }
1332
1333       fill_template (hook)
1334           Arguments are a template and a hashref.  Takes the template that
1335           was prepared using swap_template, and swaps html form fields using
1336           the passed hashref.  Overriding this method can control the fill
1337           behavior.
1338
1339           Calls the fill_args hook prior to calling CGI::Ex::Fill::fill
1340
1341       file_print (hook)
1342           Returns a filename of the content to be used in the default print
1343           hook.  Adds method base_dir_rel to hook name_module, and name_step
1344           and adds on the default file extension found in $self->ext_print
1345           which defaults to the property $self->{ext_print} which will
1346           default to ".html".  Should return a filename relative to
1347           template_path that can be swapped using Template::Alloy, or should
1348           be a scalar reference to the template content that can be swapped.
1349           This will be used by the hook print.
1350
1351               sub template_path { '/var/www/templates' }
1352               sub base_dir_rel  { 'content' }
1353               sub name_module   { 'recipe' }
1354               sub ext_print     { 'html' } # default
1355
1356               # ->file_print('this_step')
1357               # would return 'content/recipe/this_step.html'
1358               # the template engine would look in '/var/www/templates'
1359               # for a file by that name
1360
1361           It may also return a reference to a string containing the html
1362           template.  This is useful for prototyping applications and/or
1363           keeping all of the data for the application in a single location.
1364
1365       file_val (hook)
1366           Returns a filename containing the validation.  Performs the same as
1367           file_print, but uses ext_val to get the extension, and it adds
1368           vob_path (which defaults to template_path which defaults to
1369           base_dir_abs) onto the returned value (file_print is relative to
1370           template_path, while file_val is fully qualified with vob_path).
1371           If vob_path returns an arrayref of paths, then each path is checked
1372           for the existence of the file.
1373
1374           The file should be readable by CGI::Ex::Validate::get_validation.
1375
1376           This hook is only necessary if the hash_validation hook has not
1377           been overridden.  5B This method an also return a hashref
1378           containing the validation - but then you may have wanted to
1379           override the hash_validation hook.
1380
1381       finalize (hook)
1382           Defaults to true. Used to do whatever needs to be done with the
1383           data once prepare has returned true and info_complete has returned
1384           true.  On failure the print operations are ran.  On success
1385           navigation moves on to the next step.
1386
1387           This is normally were there core logic of a script will occur (such
1388           as adding to a database, or updating a record).  At this point, the
1389           data should be validated.  It is possible to do additional
1390           validation and return errors using code such as the following.
1391
1392               if (! $user_is_unique) {
1393                   $self->add_errors(username => 'The username was already used');
1394                   return 0;
1395               }
1396
1397       find_hook (method)
1398           Called by run_hook.  Arguments are a hook name, a step name.  It
1399           should return an arrayref containing the code_ref to run, and the
1400           name of the method looked for.  It uses ->can to find the
1401           appropriate hook.
1402
1403               my $code = $self->find_hook('finalize', 'main');
1404               ### will look first for $self->main_finalize;
1405               ### will then look  for $self->finalize;
1406
1407           This system is used to allow for multiple steps to be in the same
1408           file and still allow for moving some steps out to external sub
1409           classed packages (if desired).
1410
1411           If the application has successfully morphed via the morph method
1412           and allow_morph then it is not necessary to add the step name to
1413           the beginning of the method name as the morphed packages method
1414           will override the base package (it is still OK to use the full
1415           method name "${step}_hookname").
1416
1417           See the run_hook method and the morph method for more details.
1418
1419       first_step (method)
1420           Returns the first step of the path.  Note that first_step may not
1421           be the same thing as default_step if the path was overridden.
1422
1423       forbidden_step (method)
1424           Defaults to "__forbidden".  The name of a step to run should the
1425           current step name be invalid, or if a step found by the default
1426           path method is invalid.  See the path method.
1427
1428       form (method)
1429           Returns a hashref of the items passed to the CGI.  Returns
1430           $self->{form} which defaults to CGI::Ex::get_form.
1431
1432       form_name (hook)
1433           Return the name of the form to attach the js validation to.  Used
1434           by js_validation.
1435
1436       get_pass_by_user (method)
1437           This method is passed a username and the authentication object.  It
1438           should return the password for the given user.  See the
1439           get_pass_by_user method of CGI::Ex::Auth for more information.
1440           Installed as a hook to the authentication object during the
1441           get_valid_auth method.
1442
1443       get_valid_auth (method)
1444           If require_auth hook returns true on any given step then
1445           get_valid_auth will be called.
1446
1447           It will call auth_args to get some default args to pass to
1448           CGI::Ex::Auth->new.  It augments the args with sensible defaults
1449           that App already provides (such as form, cookies, and template
1450           facilities).  It also installs hooks for the get_pass_by_user,
1451           cleanup_user, and verify_user hooks of CGI::Ex::Auth.
1452
1453           It stores the $auth->last_auth_data in $self->auth_data for later
1454           use.  For example, to get the authenticated user:
1455
1456               sub require_auth { 1 }
1457
1458               sub cleanup_user {
1459                   my ($self, $user) = @_;
1460                   return lc $user;
1461               }
1462
1463               sub get_pass_by_user {
1464                   my ($self, $user) = @_;
1465                   my $pass = $self->some_method_to_get_the_pass($user);
1466                   return $pass;
1467               }
1468
1469               sub auth_args {
1470                   return {
1471                       login_header => '<h1>My login header</h1>',
1472                       login_footer => '[% TRY %][% INCLUDE login/login_footer.htm %][% CATCH %]<!-- [% error %] -->[% END %]',
1473                   };
1474               }
1475
1476               sub main_hash_swap {
1477                   my $self = shift;
1478                   my $user = $self->auth_data->{'user'};
1479                   return {user => $user};
1480               }
1481
1482           Successful authentication is cached for the duration of the
1483           nav_loop so multiple steps will run the full authentication routine
1484           only once.
1485
1486           Full customization of the login process and the login template can
1487           be done via the auth_args hash.  See the auth_args method and
1488           CGI::Ex::Auth perldoc for more information.
1489
1490       goto_step (method)
1491           This method is not normally used but can solve some difficult
1492           issues.  It provides for moving to another step at any point during
1493           the nav_loop.  Once a goto_step has been called, the entire
1494           nav_loop will be exited (to simply replace a portion of a step, you
1495           can simply run_hook('run_step', 'other_step')).  The method
1496           goto_step effectively short circuits the remaining hooks for the
1497           current step.  It does increment the recursion counter (which has a
1498           limit of ->recurse_limit - default 15).  Normally you would allow
1499           the other hooks in the loop to carry on their normal functions and
1500           avoid goto_step.  (Essentially, this hook behaves like a goto
1501           method to bypass everything else and continue at a different
1502           location in the path - there are times when it is necessary or
1503           useful to do this).
1504
1505           The method jump is an alias for this method.
1506
1507           Goto_step takes a single argument which is the location in the path
1508           to jump to.  This argument may be either a step name, the special
1509           strings "FIRST, LAST, CURRENT, PREVIOUS, OR NEXT" or the number of
1510           steps to jump forward (or backward) in the path.  The default
1511           value, 1, indicates that CGI::Ex::App should jump to the next step
1512           (the default action for goto_step).  A value of 0 would repeat the
1513           current step (watch out for recursion).  A value of -1 would jump
1514           to the previous step.  The special value of "LAST" will jump to the
1515           last step.  The special value of "FIRST" will jump back to the
1516           first step.  In each of these cases, the path array returned by
1517           ->path is modified to allow for the jumping (the path is modified
1518           so that the path history is not destroyed - if we were on step 3
1519           and jumped to one, that path would contain 1, 2, 3, *1, 2, 3, 4,
1520           etc and we would be at the *).  If a step name is not currently on
1521           the path, it will be replace any remaining steps of the path.
1522
1523               # goto previous step (repeat it)
1524               $self->goto_step($self->previous_step);
1525               $self->goto_step('PREVIOUS');
1526               $self->goto_step(-1);
1527
1528               # goto next step
1529               $self->goto_step($self->next_step);
1530               $self->goto_step('NEXT');
1531               $self->goto_step(1);
1532               $self->goto_step;
1533
1534               # goto current step (repeat)
1535               $self->goto_step($self->current_step);
1536               $self->goto_step('CURRENT');
1537               $self->goto_step(0);
1538
1539               # goto last step
1540               $self->goto_step($self->last_step);
1541               $self->goto_step('LAST');
1542
1543               # goto first step (repeat it)
1544               $self->goto_step($self->first_step);
1545               $self->goto_step('FIRST');
1546
1547       handle_error (method)
1548           If anything dies during execution, handle_error will be called with
1549           the error that had happened.  Default action is to try running the
1550           step returned by the error_step method.
1551
1552       hash_base (hook)
1553           A hash of base items to be merged with hash_form - such as pulldown
1554           menus, javascript validation, etc.  It will now also be merged with
1555           hash_fill, so it can contain default fillins as well.  It can be
1556           populated by passing a hash to ->add_to_base.  By default a sub
1557           similar to the following is what is used for hash_common.  Note the
1558           use of values that are code refs - so that the js_validation and
1559           form_name hooks are only called if requested:
1560
1561               sub hash_base {
1562                   my ($self, $step) = @_;
1563                   return $self->{hash_base} ||= {
1564                       script_name   => $ENV{SCRIPT_NAME},
1565                       js_validation => sub { $self->run_hook('js_validation', $step) },
1566                       form_name     => sub { $self->run_hook('form_name', $step) },
1567                   };
1568               }
1569
1570       hash_common (hook)
1571           Almost identical in function and purpose to hash_base.  It is
1572           intended that hash_base be used for common items used in various
1573           scripts inheriting from a common CGI::Ex::App type parent.
1574           Hash_common is more intended for step level populating of both swap
1575           and fill.
1576
1577       hash_errors (hook)
1578           Called in preparation for print after failed prepare,
1579           info_complete, or finalize.  Should contain a hash of any errors
1580           that occurred.  Will be merged into hash_form before the pass to
1581           print.  Each error that occurred will be passed to method
1582           format_error before being added to the hash.  If an error has
1583           occurred, the default validate will automatically add {has_errors
1584           =>1}.  To the error hash at the time of validation.  has_errors
1585           will also be added during the merge in case the default validate
1586           was not used.  Can be populated by passing a hash to
1587           ->add_to_errors or ->add_errors.
1588
1589       hash_fill (hook)
1590           Called in preparation for print after failed prepare,
1591           info_complete, or finalize.  Should contain a hash of any items
1592           needed to be filled into the html form during print.  Items from
1593           hash_form, hash_base, and hash_common will be layered together.
1594           Can be populated by passing a hash to ->add_to_fill.
1595
1596           By default - forms are sticky and data from previous requests will
1597           try and populate the form.  You can use the fill_template hook to
1598           disable templating on a single page or on all pages.
1599
1600           This method can be used to pre-populate the form as well (such as
1601           on an edit step).  If a form fails validation, hash_fill will also
1602           be called and will only want the submitted form fields to be
1603           sticky.  You can use the ready_validate hook to prevent pre-
1604           population in these cases as follows:
1605
1606               sub edit_hash_fill {
1607                   my $self = shift;
1608                   my $step = shift;
1609                   return {} if $self->run_hook('ready_validate', $step);
1610
1611                   my %hash;
1612
1613                   ### get previous values from the database
1614
1615                   return \%hash;
1616               }
1617
1618       hash_form (hook)
1619           Called in preparation for print after failed prepare,
1620           info_complete, or finalize.  Defaults to ->form.  Can be populated
1621           by passing a hash to ->add_to_form.
1622
1623       hash_swap (hook)
1624           Called in preparation for print after failed prepare,
1625           info_complete, or finalize.  Should contain a hash of any items
1626           needed to be swapped into the html during print.  Will be merged
1627           with hash_base, hash_common, hash_form, and hash_errors.  Can be
1628           populated by passing a hash to ->add_to_swap.
1629
1630           The hash will be passed as the second argument to swap_template.
1631
1632       hash_validation (hook)
1633           Returns a hash of the validation information to check form against.
1634           By default, will look for a filename using the hook file_val and
1635           will pass it to CGI::Ex::Validate::get_validation.  If no file_val
1636           is returned or if the get_validation fails, an empty hash will be
1637           returned.  Validation is implemented by ->vob which loads a
1638           CGI::Ex::Validate object.
1639
1640       history (method)
1641           Returns an arrayref which contains trace history of which hooks of
1642           which steps were ran.  Useful for seeing what happened.  In general
1643           - each line of the history will show the current step, the hook
1644           requested, and which hook was actually called.
1645
1646           The dump_history method shows a short condensed version of this
1647           history which makes it easier to see what path was followed.
1648
1649           In general, the arrayref is free for anything to push onto which
1650           will help in tracking other occurrences in the program as well.
1651
1652       info_complete (hook)
1653           Calls the ready_validate hook to see if data is ready to validate.
1654           If so it calls the validate hook to validate the data.  Should make
1655           sure the data is ready and valid.  Will not be run unless prepare
1656           returns true (default).
1657
1658       init (method)
1659           Called by the default new method.  Allows for any object
1660           initilizations that may need to take place.  Default action does
1661           nothing.
1662
1663       init_from_conf (method)
1664           Called by the default new method.  If load_conf is true, then the
1665           conf method will be called and the keys returned will be added to
1666           the $self object.
1667
1668           This method is called after the init method.  If you need to
1669           further fix up values added during init_from_conf, you can use the
1670           pre_navigate method.
1671
1672       insert_path (method)
1673           Arguments are the steps to insert.  Can be called any time.
1674           Inserts the new steps at the current path location.
1675
1676       is_authed (method)
1677           Returns true if the object has successful authentication data.  It
1678           returns false if the object has not been authenticated.
1679
1680       js_uri_path (method)
1681           Return the URI path where the CGI/Ex/yaml_load.js and
1682           CGI/Ex/validate.js files can be found.  This will default to
1683           "$ENV{SCRIPT_NAME}/js" if the path method has not been overridden,
1684           otherwise it will default to "$ENV{SCRIPT_NAME}?step=js&js=" (the
1685           latter is more friendly with overridden paths).  A default handler
1686           for the "js" step has been provided in "js_run_step" (this handler
1687           will nicely print out the javascript found in the js files which
1688           are included with this distribution.  js_run_step will work
1689           properly with the default "path" handler.
1690
1691       js_validation (hook)
1692           Will return Javascript that is capable of validating the form.
1693           This is done using the capabilities of CGI::Ex::Validate and
1694           CGI::Ex::JSONDump.  This will call the hook hash_validation which
1695           will then be encoded into json and placed in a javascript string.
1696           It will also call the hook form_name to determine which html form
1697           to attach the validation to.  The method js_uri_path is called to
1698           determine the path to the appropriate validate.js files.  In order
1699           to make use of js_validation, it must be added to the variables
1700           returned by either the hash_base (default), hash_common, hash_swap
1701           or hash_form hook (see examples of hash_base used in this doc).
1702
1703       jump (method)
1704           Alias for the goto_step method.
1705
1706       last_step (method)
1707           Returns the last step of the path.
1708
1709       load_conf (method)
1710           Defaults to ->{load_conf} which defaults to false.  If true, will
1711           allow keys returned by the conf method to be added to $self during
1712           the init_from_conf method.
1713
1714           Enabling this method allows for out-of-the-box file based
1715           configuration.
1716
1717       morph (method)
1718           Allows for temporarily "becoming" another object type for the
1719           execution of the current step.  This allows for separating some
1720           steps out into their own packages.
1721
1722           Morph will only run if the method allow_morph returns true.
1723           Additionally if the allow_morph returns a hash ref, morph will only
1724           run if the step being morphed to is in the hash.  Morph also passes
1725           the step name to allow_morph.
1726
1727           The morph call occurs at the beginning of the step loop.  A
1728           corresponding unmorph call occurs before the loop is exited.  An
1729           object can morph several levels deep.  For example, an object
1730           running as Foo::Bar that is looping on the step "my_step" that has
1731           allow_morph = 1, will do the following:
1732
1733               Call the morph_package hook (which would default to returning
1734               Foo::Bar::MyStep in this case)
1735
1736               Translate this to a package filename (Foo/Bar/MyStep.pm) and try
1737               and require it, if the file can be required, the object is blessed
1738               into that package.
1739
1740               Call the fixup_after_morph method.
1741
1742               Continue on with the run_step for the current step.
1743
1744           At any exit point of the loop, the unmorph call is made which re-
1745           blesses the object into the original package.
1746
1747           Samples of allowing morph:
1748
1749               sub allow_morph { 1 } # value of 1 means try to find package, ok if not found
1750
1751               sub allow_morph { {edit => 1} }
1752
1753               sub allow_morph { my ($self, $step) = @_; return $step eq 'edit' }
1754
1755       morph_package (hook)
1756           Used by morph.  Return the package name to morph into during a
1757           morph call.  Defaults to using the current object type as a base.
1758           For example, if the current object running is a Foo::Bar object and
1759           the step running is my_step, then morph_package will return
1760           Foo::Bar::MyStep.
1761
1762           Because of the way that run_hook works, it is possible that several
1763           steps could be located in the same external file and overriding
1764           morph_package could allow for this to happen.
1765
1766           See the morph method.
1767
1768       name_module (hook)
1769           Return the name (relative path) that should be pre-pended to
1770           name_step during the default file_print and file_val lookups.
1771           Defaults to the value in $self->{name_module} which in turn
1772           defaults to the name of the current script.
1773
1774               cgi-bin/my_app.pl  =>  my_app
1775               cgi/my_app         =>  my_app
1776
1777           This method is provided so that each cgi or mod_perl application
1778           can have its own directory for storing html for its steps.
1779
1780           See the file_print method for more information.
1781
1782           See the section on FINDING TEMPLATES for further discussion.
1783
1784       name_step (hook)
1785           Return the step (appended to name_module) that should used when
1786           looking up the file in file_print and file_val lookups.  Defaults
1787           to the current step.
1788
1789           See the section on FINDING TEMPLATES for further discussion.
1790
1791       nav_loop (method)
1792           This is the main loop runner.  It figures out the current path and
1793           runs all of the appropriate hooks for each step of the path.  If
1794           nav_loop runs out of steps to run (which happens if no path is set,
1795           or if all other steps run successfully), it will insert the
1796           ->default_step into the path and run nav_loop again (recursively).
1797           This way a step is always assured to run.  There is a method
1798           ->recurse_limit (default 15) that will catch logic errors (such as
1799           inadvertently running the same step over and over and over because
1800           there is either no hash_validation, or the data is valid but the
1801           set_ready_validate(0) method was not called).
1802
1803       navigate (method)
1804           Takes a class name or a CGI::Ex::App object as arguments.  If a
1805           class name is given it will call the "new" method to instantiate an
1806           object by that class (passing any extra arguments to the new
1807           method).  All returns from navigate will return the object.
1808
1809           The method navigate is essentially a safe wrapper around the
1810           ->nav_loop method.  It will catch any dies and pass them to
1811           ->handle_error.
1812
1813           This starts the process flow for the path and its steps.
1814
1815       navigate_authenticated (method)
1816           Same as the method navigate but calls ->require_auth(1) before
1817           running.  It will only work if the navigate_authenticated method
1818           has not been overwritten. See the require_auth method.
1819
1820       new (class method)
1821           Object creator.  Takes a hashref of arguments that will become the
1822           initial properties of the object.  Calls the init method once the
1823           object has been blessed to allow for any other initilizations.
1824
1825               my $app = MyApp->new({name_module => 'my_app'});
1826
1827       next_step (hook and method)
1828           As a method it returns the next step in the path - if the path has
1829           more steps left.
1830
1831           It is also used as a hook by the refine_path hook.  If there is no
1832           more steps, it will call the next_step hook to try and find a step
1833           to append to the path.
1834
1835       path (method)
1836           Return an arrayref (modifiable) of the steps in the path.  For each
1837           step the run_step hook and all of its remaining hooks will be run.
1838
1839           Hook methods are looked up and ran using the method "run_hook"
1840           which uses the method "find_hook" to lookup the hook.  A history of
1841           ran hooks is stored in the array ref returned by $self->history.
1842
1843           If path has not been defined, the method will look first in the
1844           form for a key by the name found in ->step_key.  It will then look
1845           in $ENV{'PATH_INFO'}.  It will use this step to create a path with
1846           that one step as its contents.  If a step is passed in via either
1847           of these ways, the method will call valid_steps to make sure that
1848           the step is valid (by default valid_steps returns undef - which
1849           means that any step is valid).  Any step beginning with _ can not
1850           be passed in and are intended for use on private paths.  If a non-
1851           valid step is found, then path will be set to contain a single step
1852           of ->forbidden_step.
1853
1854           For the best functionality, the arrayref returned should be the
1855           same reference returned for every call to path - this ensures that
1856           other methods can add to the path (and will most likely break if
1857           the arrayref is not the same).
1858
1859           If navigation runs out of steps to run, the default step found in
1860           default_step will be run.  This is what allows for us to default to
1861           the "main" step for many applications.
1862
1863       path_info_map (hook)
1864           Used to map path_info parts to form variables.  Similar to the
1865           path_info_map_base method.  See the path_info_map_base method for a
1866           discussion of how to use this hook.
1867
1868       path_info_map_base (method)
1869           Called during the default path method.  It is used to custom map
1870           portions of $ENV{'PATH_INFO'} to form values.  If should return an
1871           arrayref of arrayrefs where each child arrayref contains a regex qr
1872           with match parens as the first element of the array.  Subsequent
1873           elements of the array are the key names to store the corresponding
1874           matched value from the regex under.  The outer arrayref is iterated
1875           until it one of child arrayrefs matches against $ENV{'PATH_INFO'}.
1876           The matched values are only added to the form if there is not
1877           already a defined value for that key in the form.
1878
1879           The default value returned by this method looks something like the
1880           following:
1881
1882              sub path_info_map_base {
1883                  return [[qr{^/(\w+)}, $self->step_key]];
1884              }
1885
1886           This example would map the following PATH_INFO string as follows:
1887
1888              /my_step
1889
1890              # $self->form->{'step'} now equals "my_step"
1891
1892           The following is another example:
1893
1894              sub path_info_map_base {
1895                  return [
1896                      [qr{^/([^/]+)/(\w+)}, 'username', $self->step_key],
1897                      [qr{^/(\w+)}, $self->step_key],
1898                  ];
1899              }
1900
1901              # the PATH_INFO /my_step
1902              # still results in
1903              # $self->form->{'step'} now equals "my_step"
1904
1905              # but with the PATH_INFO /my_user/my_step
1906              # $self->form->{'step'} now equals "my_step"
1907              # and $self->form->{'username'} equals "my_user"
1908
1909           In most cases there is not a need to override the
1910           path_info_map_base method, but rather override the path_info_map
1911           hook for a particular step.  When the step is being run, just
1912           before the run_step hook is called, the path_info_map hook is
1913           called.  The path_info_map hook is similar to the
1914           path_info_map_base method, but is used to allow step level
1915           manipulation of form based on elements in the $ENV{'PATH_INFO'}.
1916
1917              sub my_step_path_info_map {
1918                  return [[qr{^/my_step/(\w+)$}, 'username']];
1919              }
1920
1921              # the PATH_INFO /my_step/my_user
1922              # results in
1923              # $self->form->{'step'} equal to "my_step" because of default path_info_map_base
1924              # and $self->form->{'username'} equals "my_user" because of my_step_path_info_map
1925
1926           The section on mapping URIs to steps has additional examples.
1927
1928       post_loop (method)
1929           Ran after all of the steps in the loop have been processed (if
1930           prepare, info_complete, and finalize were true for each of the
1931           steps).  If it returns a true value the navigation loop will be
1932           aborted.  If it does not return true, navigation continues by then
1933           inserting the step $self->default_step and running $self->nav_loop
1934           again (recurses) to fall back to the default step.
1935
1936       post_navigate (method)
1937           Called from within navigate.  Called after the nav_loop has
1938           finished running but within the eval block to catch errors.  Will
1939           only run if there were no errors which died during the nav_loop
1940           process.
1941
1942           It can be disabled from running by setting the _no_post_navigate
1943           property.
1944
1945           If per-step authentication is enabled and authentication fails, the
1946           post_navigate method will still be called (the post_navigate method
1947           can check the ->is_authed method to change behavior).  If
1948           application level authentication is enabled and authentication
1949           fails, none of the pre_navigate, nav_loop, or post_navigate methods
1950           will be called.
1951
1952       post_print (hook)
1953           A hook which occurs after the printing has taken place.  Is only
1954           run if the information was not complete.  Useful for cases such as
1955           printing rows of a database query after displaying a query form.
1956
1957       post_step (hook)
1958           Ran at the end of the step's loop if prepare, info_complete, and
1959           finalize all returned true.  Allows for cleanup.  If a true value
1960           is returned, execution of navigate is returned and no more steps
1961           are processed.
1962
1963       pre_loop (method)
1964           Called right before the navigation loop is started (at the
1965           beginning of nav_loop).  At this point the path is set (but could
1966           be modified).  The only argument is a reference to the path array.
1967           If it returns a true value - the navigation routine is aborted.
1968
1969       pre_navigate (method)
1970           Called at the very beginning of the navigate method, but within the
1971           eval block to catch errors.  Called before the nav_loop method is
1972           started.  If a true value is returned then navigation is skipped
1973           (the nav_loop is never started).
1974
1975       pre_step (hook)
1976           Ran at the beginning of the loop before prepare, info_compelete,
1977           and finalize are called.  If it returns true, execution of nav_loop
1978           is returned and no more steps are processed..
1979
1980       prepare (hook)
1981           Defaults to true.  A hook before checking if the info_complete is
1982           true.  Intended to be used to cleanup the form data.
1983
1984       prepared_print (hook)
1985           Called when any of prepare, info_complete, or finalize fail.
1986           Prepares a form hash and a fill hash to pass to print.  The form
1987           hash is primarily intended for use by the templating system.  The
1988           fill hash is intended to be used to fill in any html forms.
1989
1990       previous_step (method)
1991           List the step previous to this one.  Will return '' if there is no
1992           previous step.
1993
1994       print (hook)
1995           Take the information generated by prepared_print, format it using
1996           swap_template, fill it using fill_template and print it out using
1997           print_out.  Default incarnation uses Template::Alloy which is
1998           compatible with Template::Toolkit to do the swapping.  Arguments
1999           are: step name (used to call the file_print hook), swap hashref
2000           (passed to call swap_template), and fill hashref (passed to
2001           fill_template).
2002
2003           During the print call, the file_print hook is called which should
2004           return a filename or a scalar reference to the template content is
2005
2006       print_out (hook)
2007           Called with the finished document.  Should print out the
2008           appropriate headers.  The default method calls
2009           $self->cgix->print_content_type and then prints the content.
2010
2011           The print_content_type is passed $self->mimetype (which defaults to
2012           $self->{'mimetype'} which defaults to 'text/html') and
2013           $self->charset (which defaults to $self->{'charset'} which defaults
2014           to '').
2015
2016       ready_validate (hook)
2017           Should return true if enough information is present to run
2018           validate.  Default is to look if $ENV{'REQUEST_METHOD'} is 'POST'.
2019           A common usage is to pass a common flag in the form such as
2020           'processing' => 1 and check for its presence - such as the
2021           following:
2022
2023               sub ready_validate { shift->form->{'processing'} }
2024
2025           Changing the behavior of ready_validate can help in making wizard
2026           type applications.
2027
2028           You can also use the validate_when_data hook to change the behavior
2029           of ready_validate.  If valiate_when_data returns true, then
2030           ready_validate will look for keys in the form matching keys that
2031           are in hash_validation - if they exist ready_validate will be true.
2032           If there are no hash_validation keys, ready_validate uses its
2033           default behavior.
2034
2035       refine_path (hook)
2036           Called at the end of nav_loop.  Passed a single value indicating if
2037           there are currently more steps in the path.
2038
2039           The default implementation returns if there are still more steps in
2040           the path.  Otherwise, it calls the next_step hook and appends it to
2041           the path with the append_path method, and then calls the
2042           set_ready_validate hook and passes it 0.
2043
2044           This allows you to simply put
2045
2046               sub edit_next_step { '_edit_success' }
2047
2048           In your code and it will automatically do the right thing and go to
2049           the _edit_success step.
2050
2051       recurse_limit (method)
2052           Default 15.  Maximum number of times to allow nav_loop to call
2053           itself.  The recurse level will increase every time that
2054           ->goto_step is called, or if the end of the nav_loop is reached and
2055           the process tries to add the default_step and run it again.
2056
2057           If ->goto_step is used often - the recurse_limit will be reached
2058           more quickly.  It is safe to raise this as high as is necessary -
2059           so long as it is intentional.
2060
2061           Often the limit is reached if a step did not have a validation
2062           hash, or if the set_ready_validate(0) method was not called once
2063           the data had been successfully validated and acted upon.
2064
2065       replace_path (method)
2066           Arguments are the steps used to replace.  Can be called any time.
2067           Replaces the remaining steps (if any) of the current path.
2068
2069       require_auth (hook)
2070           Defaults to self->{require_auth} which defaults to undef.  If
2071           called as a method and passed a single value of 1, 0, or undef it
2072           will set the value of $self->{require_auth} to that value.  If set
2073           to a true value then any subsequent step will require
2074           authentication (unless its hook has been overwritten).
2075
2076           Any of the following ways can be used to require authentication on
2077           every step.
2078
2079               # Example one
2080               sub require_auth { 1 }
2081
2082               # Example two
2083               __PACKAGE__->navigate_authenticated; # instead of __PACKAGE__->navigate;
2084
2085               # Example three
2086               __PACKAGE__->new({require_auth => 1}->navigate;
2087
2088               # Example four
2089               sub init { shift->require_auth(1) }
2090
2091           Because it is called as a hook, the current step is passed as the
2092           first argument.  If the hook returns false, no authentication will
2093           be required on this step.  If the hook returns a true, non-hashref
2094           value, authentication will be required via the get_valid_auth
2095           method.  If the method returns a hashref of stepnames to require
2096           authentication on, the step will require authentication via the
2097           get_valid_auth method if the current step is in the hashref.  If
2098           authentication is required and succeeds, the step will proceed.  If
2099           authentication is required and fails at the step level the current
2100           step will be aborted, authentication will be asked for (the
2101           post_navigate method will still be called).
2102
2103           For example you could add authentication to the add, edit, and
2104           delete steps in any of the following ways:
2105
2106               # Example one
2107               sub require_auth { {add => 1, edit => 1, delete => 1} }
2108
2109               # Example two
2110               sub add_require_auth    { 1 }
2111               sub edit_require_auth   { 1 }
2112               sub delete_require_auth { 1 }
2113
2114               # Example three
2115               sub require_auth {
2116                   my ($self, $step) = @_;
2117                   return 1 if $step && $step =~ /^(add|edit|delete)$/;
2118                   return 0;
2119               }
2120
2121           If however you wanted to require authentication on all but one or
2122           two methods (such as requiring authentication on all but a
2123           forgot_password step) you could do either of the following:
2124
2125               # Example one
2126               sub require_auth {
2127                   my ($self, $step) = @_;
2128                   return 0 if $step && $step eq 'forgot_password';
2129                   return 1; # require auth on all other steps
2130               }
2131
2132               # Example two
2133               sub require_auth { 1 } # turn it on for all steps
2134
2135               sub forgot_password_require_auth { 0 } # turn it off
2136
2137           See the get_valid_auth method for what occurs should authentication
2138           be required.
2139
2140           There is one key difference from the 2.14 version of App.  In 2.14
2141           and previous versions, the pre_navigate and post_navigate methods
2142           would not be called if require_auth returned a true non-hashref
2143           value.  In version 2.15 and later, the 2.15 pre_navigate and
2144           post_navigate methods are always called - even if authentication
2145           fails.  Also in 2.15 and later, the method is called as a hook
2146           meaning the step is passed in.
2147
2148       run_hook (method)
2149           Arguments are a hook name and the step to find the hook for.  Calls
2150           the find_hook method to get a code ref which it then calls and
2151           returns the result passing any extra arguments to run_hook as
2152           arguments to the code ref.
2153
2154           Each call to run_hook is logged in the arrayref returned by the
2155           history method.  This information is summarized in the dump_history
2156           method and is useful for tracing the flow of the program.
2157
2158           The run_hook method is part of the core of CGI::Ex::App.  It allows
2159           for an intermediate layer in normal method calls.  Because of
2160           run_hook, it is possible to logically override methods on a step by
2161           step basis, or override a method for all of the steps, or even to
2162           break code out into separate modules.
2163
2164       run_hook_as (method)
2165           Similar to run_hook - but allows for temporarily running a hook in
2166           another package.
2167
2168               sub blah_morph_package { 'SomeOther::Module' }
2169               my $hash = $self->run_hook_as('hash_swap', 'blah'); # runs as SomeOther::Module
2170
2171               # OR
2172
2173               my $hash = $self->run_hook_as('hash_swap', 'step', 'SomeOther::Module');
2174
2175           Note that the second form will use 'SomeOther::Module' as the step
2176           name which will be somewhat misleading in looking up names.
2177
2178       run_step (hook)
2179           Runs all of the hooks specific to each step, beginning with
2180           pre_step and ending with post_step (for a full listing of steps,
2181           see the section on process flow).  Called after ->morph($step) has
2182           been run.  If this hook returns true, the nav_loop is exited
2183           (meaning the run_step hook displayed a printed page).  If it
2184           returns false, the nav_loop continues on to run the next step.
2185
2186           This hook performs the same base functionality as a method defined
2187           in CGI::Applications ->run_modes.  The default run_step method
2188           provides much more granular control over the flow of the CGI.
2189
2190       set_path (method)
2191           Arguments are the steps to set.  Should be called before navigation
2192           begins.  This will set the path arrayref to the passed steps.
2193
2194           This method is not normally used.
2195
2196       set_ready_validate (hook and method)
2197           Sets that the validation is ready (or not) to validate.  Should set
2198           the value checked by the hook ready_validate.  Has no affect if
2199           validate_when_data flag is set.
2200
2201           The following would complement the "processing" flag example given
2202           in ready_validate description:
2203
2204               sub set_ready_validate {
2205                   my $self = shift;
2206                   my ($step, $is_ready) = (@_ == 2) ? @_ : (undef, shift);
2207                   if ($is_ready) {
2208                       $self->form->{'processing'} = 1;
2209                   } else {
2210                       delete $self->form->{'processing'};
2211                   }
2212                   return $is_ready;
2213               }
2214
2215           Note that for this example the form key "processing" was deleted.
2216           This is so that the call to fill in any html forms won't swap in a
2217           value of zero for form elements named "processing."
2218
2219           Also note that this method may be called as a hook as in
2220
2221               $self->run_hook('set_ready_validate', $step, 0)
2222               # OR
2223               $self->set_ready_validate($step, 0);
2224
2225           Or it can take a single argument and should set the ready status
2226           regardless of the step as in:
2227
2228               $self->set_ready_validate(0);
2229
2230       skip (hook)
2231           Ran at the beginning of the loop before prepare, info_complete, and
2232           finalize are called.  If it returns true, nav_loop moves on to the
2233           next step (the current step is skipped).
2234
2235       stash (method)
2236           Returns a hashref that can store arbitrary user space data without
2237           worrying about overwriting the internals of the application.
2238
2239       step_key (method)
2240           Should return the keyname that will be used by the default "path"
2241           method to look for in the form.  Default value is 'step'.
2242
2243       swap_template (hook)
2244           Takes the template and hash of variables prepared in print, and
2245           processes them through the current template engine Template::Alloy.
2246
2247           Arguments are the template and the swap hashref.  The template can
2248           be either a scalar reference to the actual content, or the filename
2249           of the content.  If the filename is specified - it should be
2250           relative to template_path (which will be used to initialize
2251           INCLUDE_PATH by default).
2252
2253           The default method will create a template object by calling the
2254           template_args hook and passing the returned hashref to the
2255           template_obj method.  The default template_obj method returns a
2256           Template::Alloy object, but could easily be swapped to use a
2257           Template::Toolkit based object.  If a non-Template::Toolkit
2258           compatible object is to be used, then the swap_template hook can be
2259           overridden to use another templating engine.
2260
2261           For example to use the HTML::Template engine you could override the
2262           swap_template method as follows:
2263
2264               use HTML::Template;
2265
2266               sub swap_template {
2267                   my ($self, $step, $file, $swap) = @_;
2268
2269                   my $type = UNIVERSAL::isa($file, 'SCALAR') ? 'scalarref'
2270                            : UNIVERSAL::isa($file, 'ARRAY')  ? 'arrayref'
2271                            : ref($file)                      ? 'filehandle'
2272                            :                                   'filename';
2273
2274                   my $t = HTML::Template->new(source => $file,
2275                                               type   => $type,
2276                                               path   => $self->template_path,
2277                                               die_on_bad_params => 0,
2278                                               );
2279
2280                   $t->param($swap);
2281
2282                   return $t->output;
2283               }
2284
2285           Uou could also simply do the following to parse the templates using
2286           HTML::Template::Expr syntax.
2287
2288               sub template_args {
2289                   return {SYNTAX => 'hte'};
2290               }
2291
2292           For a listing of the available syntaxes, see the current
2293           Template::Alloy documentation.
2294
2295       template_args (hook)
2296           Returns a hashref of args that will be passed to the "new" method
2297           of Template::Alloy The method is normally called from the
2298           swap_template hook.  The swap_template hook will add a value for
2299           INCLUDE_PATH which is set equal to template_path, if the
2300           INCLUDE_PATH value is not already set.
2301
2302           The returned hashref can contain any arguments that Template::Alloy
2303           would understand.
2304
2305               sub template_args {
2306                   return {
2307                       PRE_CHOMP => 1,
2308                       WRAPPER   => 'wrappers/main_wrapper.html',
2309                   };
2310               }
2311
2312           See the Template::Alloy documentation for a listing of all possible
2313           configuration arguments.
2314
2315       template_obj (method)
2316           Called from swap_template.  It is passed the result of
2317           template_args that have had a default INCLUDE_PATH added via
2318           template_path.  The default implementation uses Template::Alloy but
2319           can easily be changed to use Template::Toolkit by using code
2320           similar to the following:
2321
2322               use Template;
2323
2324               sub template_obj {
2325                   my ($self, $args) = @_;
2326                   return Template->new($args);
2327               }
2328
2329       template_path (method)
2330           Defaults to $self->{'template_path'} which defaults to
2331           base_dir_abs.  Used by the template_obj method.
2332
2333       unmorph (method)
2334           Allows for returning an object back to its previous blessed state
2335           if the "morph" method was successful in morphing the App object.
2336           This only happens if the object was previously morphed into another
2337           object type.  Before the object is re-blessed the method
2338           fixup_before_unmorph is called.
2339
2340           See allow_morph and morph.
2341
2342       valid_steps (method)
2343           Called by the default path method.  Should return a hashref of path
2344           steps that are allowed.  If the current step is not found in the
2345           hash (or is not the default_step or js_step) the path method will
2346           return a single step of ->forbidden_step and run its hooks.  If no
2347           hash or undef is returned, all paths are allowed (default).  A key
2348           "forbidden_step" containing the step that was not valid will be
2349           placed in the stash.  Often the valid_steps method does not need to
2350           be defined as arbitrary method calls are not possible with
2351           CGI::Ex::App.
2352
2353           Any steps that begin with _ are also "not" valid for passing in via
2354           the form or path info.  See the path method.
2355
2356           Also, the pre_step, skip, prepare, and info_complete hooks allow
2357           for validating the data before running finalize.
2358
2359       validate (hook)
2360           Passed the form from $self->form.  Runs validation on the
2361           information contained in the passed form.  Uses CGI::Ex::Validate
2362           for the default validation.  Calls the hook hash_validation to load
2363           validation hashref (an empty hash means to pass validation).
2364           Should return true if the form passed validation and false
2365           otherwise.  Errors are stored as a hash in $self->{hash_errors} via
2366           method add_errors and can be checked for at a later time with
2367           method has_errors (if the default validate was used).
2368
2369           There are many ways and types to validate the data.  Please see the
2370           CGI::Ex::Validate module.
2371
2372           Upon success, it will look through all of the items which were
2373           validated, if any of them contain the keys append_path,
2374           insert_path, or replace_path, that method will be called with the
2375           value as arguments.  This allows for the validation to apply
2376           redirection to the path.  A validation item of:
2377
2378               {field => 'foo', required => 1, append_path => ['bar', 'baz']}
2379
2380           would append 'bar' and 'baz' to the path should all validation
2381           succeed.
2382
2383       validate_when_data (hook)
2384           Defaults to "validate_when_data" property which defaults to false.
2385           Called during the ready_validate hook.  If returns true,
2386           ready_validate will look for keys in the form matching keys that
2387           are in hash_validation - if they exist ready_validate will be true.
2388           If there are no hash_validation keys, ready_validate uses its
2389           default behavior.
2390
2391       verify_user (method)
2392           Installed as a hook to CGI::Ex::App during get_valid_auth.  Should
2393           return true if the user is ok.  Default is to always return true.
2394           This can be used to abort early before the get_pass_by_user hook is
2395           called.
2396
2397                sub verify_user {
2398                    my ($self, $user) = @_;
2399                    return 0 if $user eq 'paul'; # don't let paul in
2400                    return 1;                    # let anybody else in
2401                }
2402

HOW DO I SET COOKIES, REDIRECT, ETC

2404       Often in your program you will want to set cookies or bounce to a
2405       differnt URL.  This can be done using either the builtin CGI::Ex object
2406       or the built in CGI object.  It is suggested that you only use the
2407       CGI::Ex methods as it will automatically send headers and method calls
2408       under cgi, mod_perl1, or mod_perl2.  The following shows how to do
2409       basic items using the CGI::Ex object returned by the ->cgix method.
2410
2411       printing content-type headers
2412               ### CGI::Ex::App prints headers for you,
2413               ### but if you are printing custom types, you can send your own
2414               $self->cgix->print_content_type;
2415               # SAME AS
2416               # $self->cgix->print_content_type('text/html');
2417
2418       setting a cookie
2419               $self->cgix->set_cookie({
2420                   -name    => "my_key",
2421                   -value   => 'Some Value',
2422                   -expires => '1y',
2423                   -path    => '/',
2424               });
2425
2426       redirecting to another URL
2427               $self->cgix->location_bounce("http://somewhereelse.com");
2428               $self->exit_nav_loop; # normally should do this to long jump out of navigation
2429
2430       making a QUERY_STRING
2431               my $data  = {foo => "bar", one => "two or three"};
2432               my $query = $self->cgix->make_form($data);
2433               # $query now equals "foo=bar&one=two%20or%20three"
2434
2435       getting form parameters
2436               my $form = $self->form;
2437
2438           In this example $form would now contain a hashref of all POST and
2439           GET parameters passed to the server.  The form method calls
2440           $self->cgix->get_form which in turn uses CGI->param to parse
2441           values.  Fields with multiple passed values will be in the form of
2442           an arrayref.
2443
2444       getting cookies
2445               my $cookies = $self->cookies;
2446
2447           In this example $cookies would be a hashref of all passed in
2448           cookies.  The cookies method calls $self->cgix->get_cookies which
2449           in turn uses CGI->cookie to parse values.
2450
2451       See the CGI::Ex and CGI documentation for more information.
2452

COMPARISON TO OTHER APPLICATION MODULES

2454       The concepts used in CGI::Ex::App are not novel or unique.  However,
2455       they are all commonly used and very useful.  All application builders
2456       were built because somebody observed that there are common design
2457       patterns in CGI building.  CGI::Ex::App differs in that it has found
2458       more common design patterns of CGI's than other application builders
2459       and tries to get in the way less than others.
2460
2461       CGI::Ex::App is intended to be sub classed, and sub sub classed, and
2462       each step can choose to be sub classed or not.  CGI::Ex::App tries to
2463       remain simple while still providing "more than one way to do it."  It
2464       also tries to avoid making any sub classes have to call ->SUPER::
2465       (although that is fine too).
2466
2467       And if what you are doing on a particular is far too complicated or
2468       custom for what CGI::Ex::App provides, CGI::Ex::App makes it trivial to
2469       override all behavior.
2470
2471       There are certainly other modules for building CGI applications.  The
2472       following is a short list of other modules and how CGI::Ex::App is
2473       different.
2474
2475       "CGI::Application"
2476           Seemingly the most well know of application builders.  CGI::Ex::App
2477           is different in that it:
2478
2479             * Uses Template::Toolkit compatible Template::Alloy by default.
2480                 CGI::Ex::App can easily use another toolkit by simply
2481                 overriding the ->swap_template method.
2482                 CGI::Application uses HTML::Template.
2483             * Offers integrated data validation.
2484                 CGI::Application has had custom plugins created that
2485                 add some of this functionality.  CGI::Ex::App has the benefit
2486                 that validation is automatically available in javascript as well.
2487             * Allows the user to print at any time (so long as proper headers
2488                 are sent.  CGI::Application requires data to be pipelined.
2489             * Offers hooks into the various phases of each step ("mode" in
2490                 CGI::Application lingo).  CGI::Application provides only ->runmode
2491                 which is only a dispatch.
2492             * Support for easily jumping around in navigation steps.
2493             * Support for storing some steps in another package.
2494             * Integrated authentication
2495             * Integrated form filling
2496             * Integrated PATH_INFO mapping
2497
2498           CGI::Ex::App and CGI::Application are similar in that they take
2499           care of handling headers and they allow for calling other
2500           "runmodes" from within any given runmode.  CGI::Ex::App's
2501           ->run_step is essentially equivalent to a method call defined in
2502           CGI::Application's ->run_modes.  The ->run method of
2503           CGI::Application starts the application in the same manner as
2504           CGI::Ex::App's ->navigate call.  Many of the hooks around
2505           CGI::Ex::App's ->run_step call are similar in nature to those
2506           provided by CGI::Application.
2507
2508       "CGI::Prototype"
2509           There are actually many similarities.  One of the nicest things
2510           about CGI::Prototype is that it is extremely short (very very
2511           short).  The ->activate starts the application in the same manner
2512           as CGI::Ex::App's ->navigate call.  Both use Template::Toolkit as
2513           the default template system (CGI::Ex::App uses Template::Alloy
2514           which is TT compatible).  CGI::Ex::App is differrent in that it:
2515
2516             * Offers more hooks into the various phases of each step.
2517             * Support for easily jumping around in navigation steps.
2518             * Support for storing only some steps in another package.
2519             * Integrated data validation
2520             * Integrated authentication
2521             * Integrated form filling
2522             * Integrated PATH_INFO mapping
2523

SIMPLE EXTENDED EXAMPLE

2525       The following example shows the creation of a basic recipe database.
2526       It requires the use of DBD::SQLite, but that is all.  Once you have
2527       configured the db_file and template_path methods of the "recipe" file,
2528       you will have a working script that does CRUD for the recipe table.
2529       The observant reader may ask - why not use Catalyst or Ruby on Rails?
2530       The observant programmer will reply that making a framework do
2531       something simple is easy, but making it do something complex is complex
2532       and any framework that tries to do the those complex things for you is
2533       too complex.  CGI::Ex::App lets you write the complex logic but gives
2534       you the ability to not worry about the boring details such as template
2535       engines, or sticky forms, or cgi parameters, or data validation.  Once
2536       you are setup and are running, you are only left with providing the
2537       core logic of the application.
2538
2539           ### File: /var/www/cgi-bin/recipe (depending upon Apache configuration)
2540           ### --------------------------------------------
2541           #!/usr/bin/perl -w
2542
2543           use lib qw(/var/www/lib);
2544           use Recipe;
2545           Recipe->navigate;
2546
2547
2548           ### File: /var/www/lib/Recipe.pm
2549           ### --------------------------------------------
2550           package Recipe;
2551
2552           use strict;
2553           use base qw(CGI::Ex::App);
2554           use CGI::Ex::Dump qw(debug);
2555
2556           use DBI;
2557           use DBD::SQLite;
2558
2559           ###------------------------------------------###
2560
2561           sub post_navigate {
2562               # show what happened
2563               debug shift->dump_history;
2564           }
2565
2566           sub template_path { '/var/www/templates' }
2567
2568           sub base_dir_rel { 'content' }
2569
2570           sub db_file { '/var/www/recipe.sqlite' }
2571
2572           sub dbh {
2573               my $self = shift;
2574               if (! $self->{'dbh'}) {
2575                   my $file   = $self->db_file;
2576                   my $exists = -e $file;
2577                   $self->{'dbh'} = DBI->connect("dbi:SQLite:dbname=$file", '', '',
2578                                                 {RaiseError => 1});
2579                   $self->create_tables if ! $exists;
2580               }
2581               return $self->{'dbh'};
2582           }
2583
2584           sub create_tables {
2585               my $self = shift;
2586
2587               $self->dbh->do("CREATE TABLE recipe (
2588                   id INTEGER PRIMARY KEY AUTOINCREMENT,
2589                   title VARCHAR(50) NOT NULL,
2590                   ingredients VARCHAR(255) NOT NULL,
2591                   directions VARCHAR(255) NOT NULL,
2592                   date_added VARCHAR(20) NOT NULL
2593               )");
2594           }
2595
2596           ###----------------------------------------------------------------###
2597
2598           sub main_info_complete { 0 }
2599
2600           sub main_hash_swap {
2601               my $self = shift;
2602
2603               my $s = "SELECT id, title, date_added
2604                          FROM recipe
2605                         ORDER BY date_added";
2606               my $data = $self->dbh->selectall_arrayref($s);
2607               my @data = map {my %h; @h{qw(id title date_added)} = @$_; \%h} @$data;
2608
2609               return {
2610                   recipies => \@data,
2611               };
2612           }
2613
2614           ###----------------------------------------------------------------###
2615
2616           sub add_name_step { 'edit' }
2617
2618           sub add_hash_validation {
2619               return {
2620                   'group order' => [qw(title ingredients directions)],
2621                   title => {
2622                       required => 1,
2623                       max_len  => 30,
2624                   },
2625                   ingredients => {
2626                       required => 1,
2627                       max_len  => 255,
2628                   },
2629                   directions => {
2630                       required => 1,
2631                       max_len  => 255,
2632                   },
2633               };
2634           }
2635
2636           sub add_finalize {
2637               my $self = shift;
2638               my $form = $self->form;
2639
2640               my $s = "SELECT COUNT(*) FROM recipe WHERE title = ?";
2641               my ($count) = $self->dbh->selectrow_array($s, {}, $form->{'title'});
2642               if ($count) {
2643                   $self->add_errors(title => 'A recipe by this title already exists');
2644                   return 0;
2645               }
2646
2647               $s = "INSERT INTO recipe (title, ingredients, directions, date_added)
2648                     VALUES (?, ?, ?, ?)";
2649               $self->dbh->do($s, {}, $form->{'title'},
2650                                      $form->{'ingredients'},
2651                                      $form->{'directions'},
2652                                      scalar(localtime));
2653
2654               $self->add_to_form(success => "Recipe added to the database");
2655
2656               return 1;
2657           }
2658
2659           ###----------------------------------------------------------------###
2660
2661           sub edit_skip { shift->form->{'id'} ? 0 : 1 }
2662
2663           sub edit_hash_common {
2664               my $self = shift;
2665               return {} if $self->ready_validate;
2666
2667               my $sth  = $self->dbh->prepare("SELECT * FROM recipe WHERE id = ?");
2668               $sth->execute($self->form->{'id'});
2669               my $hash = $sth->fetchrow_hashref;
2670
2671               return $hash;
2672           }
2673
2674           sub edit_hash_validation { shift->add_hash_validation(@_) }
2675
2676           sub edit_finalize {
2677               my $self = shift;
2678               my $form = $self->form;
2679
2680               my $s = "SELECT COUNT(*) FROM recipe WHERE title = ? AND id != ?";
2681               my ($count) = $self->dbh->selectrow_array($s, {}, $form->{'title'}, $form->{'id'});
2682               if ($count) {
2683                   $self->add_errors(title => 'A recipe by this title already exists');
2684                   return 0;
2685               }
2686
2687               $s = "UPDATE recipe SET title = ?, ingredients = ?, directions = ? WHERE id = ?";
2688               $self->dbh->do($s, {}, $form->{'title'},
2689                                      $form->{'ingredients'},
2690                                      $form->{'directions'},
2691                                      $form->{'id'});
2692
2693               $self->add_to_form(success => "Recipe updated in the database");
2694
2695               return 1;
2696           }
2697
2698           ###----------------------------------------------------------------###
2699
2700           sub view_skip { shift->edit_skip(@_) }
2701
2702           sub view_hash_common { shift->edit_hash_common(@_) }
2703
2704           ###----------------------------------------------------------------###
2705
2706           sub delete_skip { shift->edit_skip(@_) }
2707
2708           sub delete_info_complete { 1 }
2709
2710           sub delete_finalize {
2711               my $self = shift;
2712               $self->dbh->do("DELETE FROM recipe WHERE id = ?", {}, $self->form->{'id'});
2713
2714               $self->add_to_form(success => "Recipe deleted from the database");
2715               return 1;
2716           }
2717
2718           1;
2719
2720           __END__
2721
2722
2723
2724           File: /var/www/templates/content/recipe/main.html
2725           ### --------------------------------------------
2726           <html>
2727           <head>
2728           <title>Recipe DB</title>
2729           </head>
2730           <h1>Recipe DB</h1>
2731
2732           [% IF success %]<span style="color:darkgreen"><h2>[% success %]</h2></span>[% END %]
2733
2734           <table style="border:1px solid blue">
2735           <tr><th>#</th><th>Title</th><th>Date Added</th></tr>
2736
2737           [% FOR row IN recipies %]
2738           <tr>
2739             <td>[% loop.count %].</td>
2740             <td><a href="[% script_name %]/view?id=[% row.id %]">[% row.title %]</a>
2741               (<a href="[% script_name %]/edit?id=[% row.id %]">Edit</a>)
2742             </td>
2743             <td>[% row.date_added %]</td>
2744           </tr>
2745           [% END %]
2746
2747           <tr><td colspan=2 align=right><a href="[% script_name %]/add">Add new recipe</a></td></tr>
2748           </table>
2749
2750           </html>
2751
2752
2753           File: /var/www/templates/content/recipe/edit.html
2754           ### --------------------------------------------
2755           <html>
2756           <head>
2757           <title>[% step == 'add' ? "Add" : "Edit" %] Recipe</title>
2758           </head>
2759           <h1>[% step == 'add' ? "Add" : "Edit" %] Recipe</h1>
2760
2761           <form method=post name=[% form_name %]>
2762           <input type=hidden name=step>
2763
2764           <table>
2765
2766           [% IF step != 'add' ~%]
2767           <tr>
2768             <td><b>Id:</b></td><td>[% id %]</td></tr>
2769             <input type=hidden name=id>
2770           </tr>
2771           <tr>
2772             <td><b>Date Added:</b></td><td>[% date_added %]</td></tr>
2773           </tr>
2774           [% END ~%]
2775
2776           <tr>
2777             <td valign=top><b>Title:</b></td>
2778             <td><input type=text name=title>
2779                 <span style='color:red' id=title_error>[% title_error %]</span></td>
2780           </tr>
2781           <tr>
2782             <td valign=top><b>Ingredients:</b></td>
2783             <td><textarea name=ingredients rows=10 cols=40 wrap=physical></textarea>
2784                 <span style='color:red' id=ingredients_error>[% ingredients_error %]</span></td>
2785           </tr>
2786           <tr>
2787             <td valign=top><b>Directions:</b></td>
2788             <td><textarea name=directions rows=10 cols=40 wrap=virtual></textarea>
2789                 <span style='color:red' id=directions_error>[% directions_error %]</span></td>
2790           </tr>
2791           <tr>
2792             <td colspan=2 align=right>
2793                 <input type=submit value="[% step == 'add' ? 'Add' : 'Update' %]"></td>
2794           </tr>
2795           </table>
2796           </form>
2797
2798           (<a href="[% script_name %]">Main Menu</a>)
2799           [% IF step != 'add' ~%]
2800             (<a href="[% script_name %]/delete?id=[% id %]">Delete this recipe</a>)
2801           [%~ END %]
2802
2803           [% js_validation %]
2804
2805           </html>
2806
2807
2808           File: /var/www/templates/content/recipe/view.html
2809           ### --------------------------------------------
2810           <html>
2811           <head>
2812           <title>[% title %] - Recipe DB</title>
2813           </head>
2814           <h1>[% title %]</h1>
2815           <h3>Date Added: [% date_added %]</h3>
2816
2817           <h2>Ingredients</h2>
2818           [% ingredients %]
2819
2820           <h2>Directions</h2>
2821           [% directions %]
2822
2823           <hr>
2824           (<a href="[% script_name %]">Main Menu</a>)
2825           (<a href="[% script_name %]/edit?id=[% id %]">Edit this recipe</a>)
2826
2827           </html>
2828
2829           ### --------------------------------------------
2830
2831       Notes:
2832
2833       The dbh method returns an SQLite dbh handle and auto creates the
2834       schema.  You will normally want to use MySQL or Oracle, or Postgres and
2835       you will want your schema to NOT be auto-created.
2836
2837       This sample uses hand rolled SQL.  Class::DBI or a similar module might
2838       make this example shorter.  However, more complex cases that need to
2839       involve two or three or four tables would probably be better off using
2840       the hand crafted SQL.
2841
2842       This sample uses SQL.  You could write the application to use whatever
2843       storage you want - or even to do nothing with the submitted data.
2844
2845       We had to write our own HTML (Catalyst and Ruby on Rails do this for
2846       you).  For most development work - the HTML should be in a static
2847       location so that it can be worked on by designers.  It is nice that the
2848       other frameworks give you stub html - but that is all it is.  It is
2849       worth about as much as copying and pasting the above examples.  All
2850       worthwhile HTML will go through a non-automated design/finalization
2851       process.
2852
2853       The add step used the same template as the edit step.  We did this
2854       using the add_name_step hook which returned "edit".  The template
2855       contains IF conditions to show different information if we were in add
2856       mode or edit mode.
2857
2858       We reused code, validation, and templates.  Code and data reuse is a
2859       good thing.
2860
2861       The edit_hash_common returns an empty hashref if the form was ready to
2862       validate.  When hash_common is called and the form is ready to
2863       validate, that means the form failed validation and is now printing out
2864       the page.  To let us fall back and use the "sticky" form fields that
2865       were just submitted, we need to not provide values in the hash_common
2866       method.
2867
2868       We use hash_common.  Values from hash_common are used for both template
2869       swapping and filling.  We could have used hash_swap and hash_fill
2870       independently.
2871
2872       The hook main_info_complete is hard coded to 0.  This basically says
2873       that we will never try and validate or finalize the main step - which
2874       is most often the case.
2875

SEPARATING STEPS INTO SEPARATE FILES

2877       It may be useful sometimes to separate some or all of the steps of an
2878       application into separate files.  This is the way that CGI::Prototype
2879       works.  This is useful in cases were some steps and their hooks are
2880       overly large - or are seldom used.
2881
2882       The following modifications can be made to the previous "recipe db"
2883       example that would move the "delete" step into its own file.  Similar
2884       actions can be taken to break other steps into their own file as well.
2885
2886           ### File: /var/www/lib/Recipe.pm
2887           ### Same as before but add the following line:
2888           ### --------------------------------------------
2889
2890           sub allow_morph { 1 }
2891
2892
2893           ### File: /var/www/lib/Recipe/Delete.pm
2894           ### Remove the delete_* subs from lib/Recipe.pm
2895           ### --------------------------------------------
2896           package Recipe::Delete;
2897
2898           use strict;
2899           use base qw(Recipe);
2900
2901           sub skip { shift->edit_skip(@_) }
2902
2903           sub info_complete { 1 }
2904
2905           sub finalize {
2906               my $self = shift;
2907               $self->dbh->do("DELETE FROM recipe WHERE id = ?", {}, $self->form->{'id'});
2908
2909               $self->add_to_form(success => "Recipe deleted from the database");
2910               return 1;
2911           }
2912
2913       Notes:
2914
2915       The hooks that are called (skip, info_complete, and finalize) do not
2916       have to be prefixed with the step name because they are now in their
2917       own individual package space.  However, they could still be named
2918       delete_skip, delete_info_complete, and delete_finalize and the run_hook
2919       method will find them (this would allow several steps with the same
2920       "morph_package" to still be stored in the same external module).
2921
2922       The method allow_morph is passed the step that we are attempting to
2923       morph to.  If allow_morph returns true every time, then it will try and
2924       require the extra packages every time that step is ran.  You could
2925       limit the morphing process to run only on certain steps by using code
2926       similar to the following:
2927
2928           sub allow_morph { return {delete => 1} }
2929
2930           # OR
2931
2932           sub allow_morph {
2933               my ($self, $step) = @_;
2934               return ($step eq 'delete') ? 1 : 0;
2935           }
2936
2937       The CGI::Ex::App temporarily blesses the object into the
2938       "morph_package" for the duration of the step and re-blesses it into the
2939       original package upon exit.  See the morph method and allow_morph for
2940       more information.
2941

RUNNING UNDER MOD_PERL

2943       The previous samples are essentially suitable for running under flat
2944       CGI, Fast CGI, or mod_perl Registry or mod_perl PerlRun type
2945       environments.  It is very easy to move the previous example to be a
2946       true mod_perl handler.
2947
2948       To convert the previous recipe example, simply add the following:
2949
2950           ### File: /var/www/lib/Recipe.pm
2951           ### Same as before but add the following lines:
2952           ### --------------------------------------------
2953
2954           sub handler {
2955               Recipe->navigate;
2956               return;
2957           }
2958
2959
2960           ### File: apache2.conf - or whatever your apache conf file is.
2961           ### --------------------------------------------
2962           <Location /recipe>
2963               SetHandler perl-script
2964               PerlHandler Recipe
2965           </Location>
2966
2967       Notes:
2968
2969       Both the /cgi-bin/recipe version and the /recipe version can co-exist.
2970       One of them will be a normal cgi and the other will correctly use
2971       mod_perl hooks for headers.
2972
2973       Setting the location to /recipe means that the $ENV{SCRIPT_NAME} will
2974       also be set to /recipe.  This means that name_module method will
2975       resolve to "recipe".  If a different URI location is desired such as
2976       "/my_cool_recipe" but the program is to use the same template content
2977       (in the /var/www/templates/content/recipe directory), then we would
2978       need to explicitly set the "name_module" parameter.  It could be done
2979       in either of the following ways:
2980
2981           ### File: /var/www/lib/Recipe.pm
2982           ### Same as before but add the following line:
2983           ### --------------------------------------------
2984
2985           sub name_module { 'recipe' }
2986
2987           # OR
2988
2989           sub init {
2990               my $self = shift;
2991               $self->{'name_module'} = 'recipe';
2992           }
2993
2994       In most use cases it isn't necessary to set name_module, but it also
2995       doesn't hurt and in all cases it is more descriptive to anybody who is
2996       going to maintain the code later.
2997

ADDING AUTHENTICATION TO THE ENTIRE APPLICATION

2999       Having authentication is sometimes a good thing.  To force the entire
3000       application to be authenticated (require a valid username and password
3001       before doing anything) you could do the following.
3002
3003           ### File: /var/www/lib/Recipe.pm
3004           ### Same as before but add
3005           ### --------------------------------------------
3006
3007           sub get_pass_by_user {
3008               my $self = shift;
3009               my $user = shift;
3010               my $pass = $self->lookup_and_cache_the_pass($user);
3011               return $pass;
3012           }
3013
3014
3015           ### File: /var/www/cgi-bin/recipe (depending upon Apache configuration)
3016           ### Change the line with ->navigate; to
3017           ### --------------------------------------------
3018
3019           Recipe->navigate_authenticated;
3020
3021           # OR
3022
3023           ### File: /var/www/lib/Recipe.pm
3024           ### Same as before but add
3025           ### --------------------------------------------
3026
3027           sub require_auth { 1 }
3028
3029           # OR
3030
3031           ### File: /var/www/lib/Recipe.pm
3032           ### Same as before but add
3033           ### --------------------------------------------
3034
3035           sub init { shift->require_auth(1) }
3036
3037       See the require_auth, get_valid_auth, and auth_args methods for more
3038       information.  Also see the CGI::Ex::Auth perldoc.
3039

ADDING AUTHENTICATION TO INDIVIDUAL STEPS

3041       Sometimes you may only want to have certain steps require
3042       authentication.  For example, in the previous recipe example we might
3043       want to let the main and view steps be accessible to anybody, but
3044       require authentication for the add, edit, and delete steps.
3045
3046       To do this, we would do the following to the original example (the
3047       navigation must start with ->navigate.  Starting with
3048       ->navigate_authenticated will cause all steps to require validation):
3049
3050           ### File: /var/www/lib/Recipe.pm
3051           ### Same as before but add
3052           ### --------------------------------------------
3053
3054           sub get_pass_by_user {
3055               my $self = shift;
3056               my $user = shift;
3057               my $pass = $self->lookup_and_cache_the_pass($user);
3058               return $pass;
3059           }
3060
3061           sub require_auth { {add => 1, edit => 1, delete => 1} }
3062
3063       We could also enable authentication by using individual hooks as in:
3064
3065           sub add_require_auth    { 1 }
3066           sub edit_require_auth   { 1 }
3067           sub delete_require_auth { 1 }
3068
3069       Or we could require authentication on everything - but let a few steps
3070       in:
3071
3072           sub require_auth { 1 }      # turn authentication on for all
3073           sub main_require_auth { 0 } # turn it off for main and view
3074           sub view_require_auth { 0 }
3075
3076       That's it.  The add, edit, and delete steps will now require
3077       authentication.  See the require_auth, get_valid_auth, and auth_args
3078       methods for more information.  Also see the CGI::Ex::Auth perldoc.
3079

THANKS

3081       The following corporation and individuals contributed in some part to
3082       the original versions.
3083
3084           Bizhosting.com  - giving a problem that fit basic design patterns.
3085
3086           Earl Cahill     - pushing the idea of more generic frameworks.
3087
3088           Adam Erickson   - design feedback, bugfixing, feature suggestions.
3089
3090           James Lance     - design feedback, bugfixing, feature suggestions.
3091
3092           Krassimir Berov - feedback and some warnings issues with POD examples.
3093

LICENSE

3095       This module may be distributed under the same terms as Perl itself.
3096

AUTHOR

3098       Paul Seamons <perl at seamons dot com>
3099
3100
3101
3102perl v5.32.1                      2021-01-26                   CGI::Ex::App(3)
Impressum