blib/lib/Titanium.pm untested

filter: Statementstmt 0.0% 0 / 46 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 0.0% 0 / 15 Podpod n/a totaltotal 0.0% 0 / 61 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Titanium;
2 use base 'CGI::Application';
3  
4 use vars '$VERSION';
5 $VERSION = '1.04';
6  
7 # Just load a few recommended plugins by default.
8 use CGI::Application::Plugin::Forward;
9 use CGI::Application::Plugin::Redirect;
10 use CGI::Application::Plugin::Session;
11 use CGI::Application::Plugin::ValidateRM;
12 use CGI::Application::Plugin::ConfigAuto 'cfg';
13 use CGI::Application::Plugin::FillInForm 'fill_form';
14 use CGI::Application::Plugin::ErrorPage 'error';
15 use CGI::Application::Plugin::Stream 'stream_file';
16 use CGI::Application::Plugin::DBH qw(dbh_config dbh);
17 use CGI::Application::Plugin::LogDispatch;
18  
19 # For development, need to activated with an ENV variable.
20 use CGI::Application::Plugin::DebugScreen;
21 use CGI::Application::Plugin::DevPopup;
22 use CGI::Application::Standard::Config;
23  
24  
25  
26 =head1 NAME
27  
28 Titanium - A strong, lightweight web application framework
29  
30 =head1 SYNOPSIS
31  
32 =head2 Coding
33  
34 # In "WebApp.pm"...
35 package WebApp;
36 use base 'Titanium';
37  
38 sub setup {
39 my $c = shift;
40  
41 $c->start_mode('form_display');
42 $c->run_modes([qw/
43 form_display
44 form_process
45 /]);
46 }
47 sub form_display {
48 my $c = shift;
49 my $errs = shift;
50  
51 my $t = $c->load_tmpl;
52 $t->param($errs) if $errs;
53 return $t->output;
54 }
55 sub form_process {
56 my $c = shift;
57  
58 # Validate the form against a profile. If it fails validation, re-display
59 # the form for the user with their data pre-filled and the errors highlighted.
60 my ($results, $err_page) = $c->check_rm('form_display','_form_profile');
61 return $err_page if $err_page;
62  
63 return $c->forward('form_success');
64 }
65  
66 # Return a Data::FormValidator profile
67 sub _form_profile {
68 my $c = shift;
69 return {
70 required => 'email',
71 };
72 }
73  
74 sub form_success { ... }
75  
76 1;
77  
78 ### In "webapp.cgi"...
79 use WebApp;
80 my $c = WebApp->new();
81 $c->run();
82  
83 Inside the run modes, the following methods are available:
84  
85 $c->query; # A query object. CGI.pm by default.
86 $c->redirect('http://othersite.com'); # Basic redirection
87 $c->dbh; # DBI database handle
88 $c->session(); # A CGI::Session object
89 $c->check_rm; # Form validation with Data::FormValidator
90 $c->cfg('root_uri'); # Config file access (YAML, Perl or INI formats)
91 $c->fill_form; # Form filling with HTML::FillInForm
92 $c->error( title => '..', msg => '..' ); # Easy error page generation
93 $c->stream_file($file); # file streaming
94 $c->log; # A Log::Dispatch object
95  
96 =head2 Development and Testing
97  
98 Easily setup the project skeleton using the bundled L<cgiapp-starter> script.
99  
100 In development you can turn on a debugging screen and a developer pop-up to quickly catch
101 code, html and performance issues, thanks to L<CGI::Application::Plugin::DebugScreen|CGI::Application::Plugin::DebugScreen> and
102 L<CGI::Application::Plugin::DevPopup|CGI::Application::Plugin::DevPopup>.
103  
104 For automated testing, L<Test::WWW::Mechanize::CGIApp|Test::WWW::Mechanize::CGIApp> is bundled, allowing you
105 to functionally test your web application without involving a full web server.
106 If you'd rather test against full web server, L<Test::WWW::Mechanize|Test::WWW::Mechanize> is there, too.
107  
108 =head2 Dispatching with Clean URIs
109  
110 Modern web frameworks dispense with cruft in URIs. Instead of:
111  
112 /cgi-bin/item.cgi?rm=view&id=15
113  
114 A clean URI to describe the same resource might be:
115  
116 /item/15/view
117  
118 The process of mapping these URIs to run modes is called dispatching and is
119 handled by L<CGI::Application::Dispatch|CGI::Application::Dispatch>. It comes
120 with a default dispatch table that automatically creates URLs in this pattern
121 for you:
122  
123 /app/module_name/run_mode
124  
125 There's plenty of flexibility to design your own URIs if you'd like.
126  
127 =head1 Elements of Titanium
128  
129 * B<Titanium is solid and mature>. While it has a new name, the reality is that
130 Titanium is simply a more user-friendly packaging of the mature
131 CGI::Application framework and some useful plugins. These packages have already
132 been refined and vetted. The seed framework was first released in 2000 and by
133 2005 was mature. Titanium contains no real code of its own, and there is no
134 intention to do so in the future. Instead, we may select other mature plugins
135 to include in the future. Other "Titanium alloys" in the "Titanium::Alloy::"
136 name space may also come to exist, following the same philosophy, but choosing
137 to bundle a different combination of plugins.
138  
139 * B<Titanium is lightweight>. Titanium has a very light core and the plugins it
140 uses employ lazy-loading whenever possible. That means that while we have
141 built-in database plugin, we don't have to load DBI or make a database
142 connection until you actually use the database connection. Titanium runs well
143 in a plain CGI environment and provides excellent performance in a persistent
144 environment such as FastCGI or mod_perl. Titanium apps are compatible with the
145 dozens of published plugins for L<CGI::Application|CGI::Application>, so you
146 can add additional features as your needs evolve.
147  
148 =head1 DESCRIPTION
149  
150 It is intended that your Application Module will be implemented as a sub-class
151 of Titanium. This is done simply as follows:
152  
153 package My::App;
154 use base 'Titanium';
155  
156 B<Notation and Conventions>
157  
158 For the purpose of this document, we will refer to the
159 following conventions:
160  
161 WebApp.pm : The Perl module which implements your Application Module class.
162 WebApp : Your Application Module class; a sub-class of Titanium.
163 webapp.cgi : The Instance Script which implements your Application Module.
164 $c : Used in instance methods to pass around the
165 current object. (Sometimes referred as "$self" in other projects.)
166 Think of the "$c" as short for "controller".
167  
168  
169 =head2 Script/Dispatching Methods
170  
171 By inheriting from Titanium you have access to a number of built-in methods.
172 The following are those which are expected to be called from your Instance
173 Script or through your L<CGI::Application::Dispatch|CGI::Application::Dispatch>
174 dispatcher.
175  
176 =head3 new()
177  
178 The new() method is the constructor for a Titanium. It returns
179 a blessed reference to your Application Module class. Optionally,
180 new() may take a set of parameters as key => value pairs:
181  
182 my $c = WebApp->new(
183 TMPL_PATH => 'App/',
184 PARAMS => {
185 'custom_thing_1' => 'some val',
186 'another_custom_thing' => [qw/123 456/]
187 }
188 );
189  
190 This method may take some specific parameters:
191  
192 B<TMPL_PATH> - This optional parameter defines a path to a directory of templates.
193 This is used by the load_tmpl() method (specified below), and may also be used
194 for the same purpose by other template plugins. This run-time parameter allows
195 you to further encapsulate instantiating templates, providing potential for
196 more re-usability. It can be either a scalar or an array reference of multiple
197 paths.
198  
199 B<QUERY> - This optional parameter allows you to specify an already-created CGI
200 query object. Under normal use, Titanium will instantiate its own
201 L<CGI.pm|CGI.pm> query object. Under certain conditions, it might be useful to
202 be able to use one which has already been created.
203  
204 B<PARAMS> - This parameter, if used, allows you to set a number
205 of custom parameters at run-time. By passing in different
206 values in different instance scripts which use the same application
207 module you can achieve a higher level of re-usability. For instance,
208 imagine an application module, "Mailform.pm". The application takes
209 the contents of a HTML form and emails it to a specified recipient.
210 You could have multiple instance scripts throughout your site which
211 all use this "Mailform.pm" module, but which set different recipients
212 or different forms.
213  
214 One common use of instance scripts is to provide a path to a config file. This
215 design allows you to define project wide configuration objects used by many
216 several instance scripts. There are several plugins which simplify the syntax
217 for this and provide lazy loading. Here's an example using
218 L<CGI::Application::Plugin::ConfigAuto|CGI::Application::Plugin::ConfigAuto>,
219 which uses L<Config::Auto|Config::Auto> to support many configuration file
220 formats.
221  
222 my $app = WebApp->new(PARAMS => { cfg_file => 'config.pl' });
223  
224 # Later in your app:
225 my %cfg = $c->cfg()
226 # or ... $c->cfg('HTML_ROOT_DIR');
227  
228 See the list of of plugins below for more config file integration solutions.
229  
230 =head3 run()
231  
232 The run() method is called upon your Application Module object, from
233 your Instance Script. When called, it executes the functionality
234 in your Application Module.
235  
236 my $c = WebApp->new;
237 $c->run;
238  
239 This method determines the application state by looking at the dispatch table,
240 as described in L<CGI::Application::Dispatch|CGI::Application::Dispatch>.
241  
242 Once the mode has been determined, run() looks at the hash stored in
243 run_modes() and finds the subroutine which is tied to a specific hash key. If
244 found, the function is called and the data returned is print()'ed to STDOUT and
245 to the browser. If the specified mode is not found in the run_modes() table,
246 run() will croak(). This 'death' can possibly be captured and handled using C<error_mode()>,
247 described below.
248  
249 =head2 Essential Method to Override
250  
251 Titanium implements some methods which are expected to be overridden
252 by implementing them in your sub-class module. One of these is essential to do:
253  
254 =head3 setup()
255  
256 This method is called by the inherited new() constructor method. The
257 setup() method should be used to define the following property/methods:
258  
259 start_mode() - string containing the default run mode.
260 run_modes() - hash table containing mode => function mappings.
261  
262 error_mode() - string containing the error mode.
263 tmpl_path() - string or array reference containing path(s) to template directories.
264  
265 Your setup() method may call any of the instance methods of your application.
266 This function is a good place to define properties specific to your application
267 via the $c->param() method.
268  
269 Your setup() method might be implemented something like this:
270  
271 sub setup {
272 my $c = shift;
273 $c->start_mode('putform');
274 $c->run_modes([qw/
275 form
276 form_process
277 /]);
278 }
279  
280 =head2 Essential Application Methods
281  
282 The following methods are inherited from Titanium, and are
283 available to be called by your application within your Application
284 Module. They are called essential because you will use all are most
285 of them to get any application up and running. These functions are listed in alphabetical order.
286  
287 =head3 load_tmpl()
288  
289 my $tmpl_obj = $c->load_tmpl;
290 my $tmpl_obj = $c->load_tmpl('some.html');
291 my $tmpl_obj = $c->load_tmpl( \$template_content );
292 my $tmpl_obj = $c->load_tmpl( FILEHANDLE );
293  
294 This method takes the name of a template file, a reference to template data
295 or a FILEHANDLE and returns an HTML::Template object. If the filename is undefined or missing, Titanium will default to trying to use the current run mode name, plus the extension ".html".
296  
297 If you use the default template naming system, you should also use
298 L<CGI::Application::Plugin::Forward>, which simply helps to keep the current
299 name accurate when you pass control from one run mode to another.
300  
301 ( For integration with other template systems
302 and automated template names, see "Alternatives to load_tmpl() below. )
303  
304 When you pass in a filename, the HTML::Template->new_file() constructor
305 is used for create the object. When you pass in a reference to the template
306 content, the HTML::Template->new_scalar_ref() constructor is used and
307 when you pass in a filehandle, the HTML::Template->new_filehandle()
308 constructor is used.
309  
310 Refer to L<HTML::Template> for specific usage of HTML::Template.
311  
312 If tmpl_path() has been specified, load_tmpl() will set the
313 HTML::Template C<path> option to the path(s) provided. This further
314 assists in encapsulating template usage.
315  
316 The load_tmpl() method will pass any extra parameters sent to it directly to
317 HTML::Template->new_file() (or new_scalar_ref() or new_filehandle()).
318 This will allow the HTML::Template object to be further customized:
319  
320 my $tmpl_obj = $c->load_tmpl('some_other.html',
321 die_on_bad_params => 0,
322 cache => 1
323 );
324  
325 Note that if you want to pass extra arguments but use the default template
326 name, you still need to provide a name of C<undef>:
327  
328 my $tmpl_obj = $c->load_tmpl(undef',
329 die_on_bad_params => 0,
330 cache => 1
331 );
332  
333 B<Alternatives to load_tmpl()>
334  
335 If your application requires more specialized behavior than this, you can
336 always replace it by overriding load_tmpl() by implementing your own
337 load_tmpl() in your Titanium sub-class application module.
338  
339 First, you may want to check out the template related plugins.
340  
341 L<CGI::Application::Plugin::TT> focuses just on Template Toolkit integration,
342 and features pre-and-post features, singleton support and more.
343  
344 =head3 param()
345  
346 $c->param('pname', $somevalue);
347  
348 The param() method provides a facility through which you may set
349 application instance properties which are accessible throughout
350 your application.
351  
352 The param() method may be used in two basic ways. First, you may use it
353 to get or set the value of a parameter:
354  
355 $c->param('scalar_param', '123');
356 my $scalar_param_values = $c->param('some_param');
357  
358 Second, when called in the context of an array, with no parameter name
359 specified, param() returns an array containing all the parameters which
360 currently exist:
361  
362 my @all_params = $c->param();
363  
364 The param() method also allows you to set a bunch of parameters at once
365 by passing in a hash (or hashref):
366  
367 $c->param(
368 'key1' => 'val1',
369 'key2' => 'val2',
370 'key3' => 'val3',
371 );
372  
373 The param() method enables a very valuable system for customizing your
374 applications on a per-instance basis. One Application Module might be
375 instantiated by different Instance Scripts. Each Instance Script might set
376 different values for a set of parameters. This allows similar applications to
377 share a common code-base, but behave differently. For example, imagine a mail
378 form application with a single Application Module, but multiple Instance
379 Scripts. Each Instance Script might specify a different recipient. Another
380 example would be a web bulletin boards system. There could be multiple boards,
381 each with a different topic and set of administrators.
382  
383 The new() method provides a shortcut for specifying a number of run-time
384 parameters at once. Internally, Titanium calls the param()
385 method to set these properties. The param() method is a powerful tool for
386 greatly increasing your application's re-usability.
387  
388 =head3 query()
389  
390 my $q = $c->query();
391 my $remote_user = $q->remote_user();
392  
393 This method retrieves the CGI.pm query object which has been created
394 by instantiating your Application Module. For details on usage of this
395 query object, refer to L<CGI>. Titanium is built on the CGI
396 module. Generally speaking, you will want to become very familiar
397 with CGI.pm, as you will use the query object whenever you want to
398 interact with form data.
399  
400 When the new() method is called, a CGI query object is automatically created.
401 If, for some reason, you want to use your own CGI query object, the new()
402 method supports passing in your existing query object on construction using
403 the QUERY attribute.
404  
405  
406 =head3 run_modes()
407  
408 # The common usage: an arrayref of run mode names that exactly match subroutine names
409 $c->run_modes([qw/
410 form_display
411 form_process
412 /]);
413  
414 # With a hashref, use a different name or a code ref
415 $c->run_modes(
416 'mode1' => 'some_sub_by_name',
417 'mode2' => \&some_other_sub_by_ref
418 );
419  
420 This accessor/mutator specifies a lookup table for the application states,
421 using the syntax examples above. It returns the dispatch table as a hash.
422  
423 The run_modes() method may be called more than once. Additional values passed
424 into run_modes() will be added to the run modes table. In the case that an
425 existing run mode is re-defined, the new value will override the existing value.
426 This behavior might be useful for applications which are created via inheritance
427 from another application, or some advanced application which modifies its
428 own capabilities based on user input.
429  
430 The run() method uses the data in this table to send the application to the
431 correct function as determined by the dispatcher, as described in
432 L<CGI::Application::Dispatch|CGI::Application::Dispatch>. These functions are
433 referred to as "run mode methods".
434  
435 The hash table set by this method is expected to contain the mode
436 name as a key. The value should be either a hard reference (a subref)
437 to the run mode method which you want to be called when the application enters
438 the specified run mode, or the name of the run mode method to be called:
439  
440 'mode_name_by_ref' => \&mode_function
441 'mode_name_by_name' => 'mode_function'
442  
443 The run mode method specified is expected to return a block of text (e.g.:
444 HTML) which will eventually be sent back to the web browser. The run mode
445 method may return its block of text as a scalar or a scalar-ref.
446  
447 An advantage of specifying your run mode methods by name instead of
448 by reference is that you can more easily create derivative applications
449 using inheritance. For instance, if you have a new application which is
450 exactly the same as an existing application with the exception of one
451 run mode, you could simply inherit from that other application and override
452 the run mode method which is different. If you specified your run mode
453 method by reference, your child class would still use the function
454 from the parent class.
455  
456 An advantage of specifying your run mode methods by reference instead of by name
457 is performance. Dereferencing a subref is faster than eval()-ing
458 a code block. If run-time performance is a critical issue, specify
459 your run mode methods by reference and not by name. The speed differences
460 are generally small, however, so specifying by name is preferred.
461  
462 Specifying the run modes by array reference:
463  
464 $c->run_modes([ 'mode1', 'mode2', 'mode3' ]);
465  
466 Is is the same as using a hash, with keys equal to values
467  
468 $c->run_modes(
469 'mode1' => 'mode1',
470 'mode2' => 'mode2',
471 'mode3' => 'mode3'
472 );
473  
474 Often, it makes good organizational sense to have your run modes map to
475 methods of the same name. The array-ref interface provides a shortcut
476 to that behavior while reducing verbosity of your code.
477  
478 Note that another importance of specifying your run modes in either a
479 hash or array-ref is to assure that only those Perl methods which are
480 specifically designated may be called via your application. Application
481 environments which don't specify allowed methods and disallow all others
482 are insecure, potentially opening the door to allowing execution of
483 arbitrary code. Titanium maintains a strict "default-deny" stance
484 on all method invocation, thereby allowing secure applications
485 to be built upon it.
486  
487 B<IMPORTANT NOTE ABOUT RUN MODE METHODS>
488  
489 Your application should *NEVER* print() to STDOUT.
490 Using print() to send output to STDOUT (including HTTP headers) is
491 exclusively the domain of the inherited run() method. Breaking this
492 rule is a common source of errors. If your program is erroneously
493 sending content before your HTTP header, you are probably breaking this rule.
494  
495  
496 B<THE RUN MODE OF LAST RESORT: "AUTOLOAD">
497  
498 If Titanium is asked to go to a run mode which doesn't exist,
499 by default it will return an error page to the user, implemented
500 like this:
501  
502 return $c->error(
503 title => 'The requested page was not found.',
504 msg => "(The page tried was: ".$c->get_current_runmode.")"
505 );
506  
507 See L<CGI::Application::Plugin::ErrorPage> for more details on the built-in
508 error page system. If this is not your desired behavior for handling unknown
509 run mode requests, implement your own run mode with the reserved name
510 "AUTOLOAD":
511  
512 $c->run_modes(
513 "AUTOLOAD" => \&catch_my_exception
514 );
515  
516 Before Titanium invokes its own error page handling it will check for the
517 existence of a run mode called "AUTOLOAD". If specified, this run mode will in
518 invoked just like a regular run mode, with one exception: It will receive, as
519 an argument, the name of the run mode which invoked it:
520  
521 sub catch_my_exception {
522 my $c = shift;
523 my $intended_runmode = shift;
524  
525 my $output = "Looking for '$intended_runmode', but found 'AUTOLOAD' instead";
526 return $output;
527 }
528  
529 This functionality could be for more sophisticated application behaviors.
530  
531 =head3 start_mode()
532  
533 $c->start_mode('mode1');
534  
535 The start_mode contains the name of the mode as specified in the run_modes()
536 table. Default mode is "start". The mode key specified here will be used
537 whenever the value of the CGI form parameter specified by mode_param() is
538 not defined. Generally, this is the first time your application is executed.
539  
540 =head3 tmpl_path()
541  
542 $c->tmpl_path('/path/to/some/templates/');
543  
544 This access/mutator method sets the file path to the directory (or directories)
545 where the templates are stored. It is used by load_tmpl() to find the template
546 files, using HTML::Template's C<path> option. To set the path you can either
547 pass in a text scalar or an array reference of multiple paths.
548  
549  
550  
551  
552 =head2 More Methods to override
553  
554 Several more non-essential methods are useful to declare in your application
555 class, or in a project "super class" that inherits from your Titanium only to
556 serve in turn as a base class for project modules. These additional methods are
557 as follows:
558  
559 =head3 teardown()
560  
561 If implemented, this method is called automatically after your application
562 runs. It can be used to clean up after your operations. A typical use of the
563 teardown() function is to disconnect a database connection which was
564 established in the setup() function, or flush open session data. You could
565 also use the teardown() method to store state information about the application
566 to the server.
567  
568 =head3 cgiapp_init()
569  
570 If implemented, this method is called automatically right before the setup()
571 method is called. The cgiapp_init() method receives, as its parameters, all
572 the arguments which were sent to the new() method.
573  
574 An example of the benefits provided by utilizing this hook is
575 creating a custom "application super-class" from which which all
576 your web applications would inherit, instead of directly from Titanium.
577  
578 Consider the following:
579  
580 # In MySuperclass.pm:
581 package MySuperclass;
582 use base 'Titanium';
583 sub cgiapp_init {
584 my $c = shift;
585 # Perform some project-specific init behavior
586 # such as to load settings from a database or file.
587 }
588  
589  
590 # In MyApplication.pm:
591 package MyApplication;
592 use base 'MySuperclass';
593 sub setup { ... }
594 sub teardown { ... }
595 # The rest of your Titanium-based follows...
596  
597  
598 By using Titanium and the cgiapp_init() method as illustrated,
599 a suite of applications could be designed to share certain
600 characteristics, creating cleaner code.
601  
602 =head3 cgiapp_prerun()
603  
604 If implemented, this method is called automatically right before the selected
605 run mode method is called. This method provides an optional pre-runmode hook,
606 which permits functionality to be added at the point right before the run mode
607 method is called. The value of the run mode is passed into cgiapp_prerun().
608  
609 This could be used by a custom "application super-class" from which all your
610 web applications would inherit, instead of Titanium.
611  
612 Consider the following:
613  
614 # In MySuperclass.pm:
615 package MySuperclass;
616 use base 'Titanium';
617 sub cgiapp_prerun {
618 my $c = shift;
619 # Perform some project-specific init behavior
620 # such as to implement run mode specific
621 # authorization functions.
622 }
623  
624  
625 # In MyApplication.pm:
626 package MyApplication;
627 use base 'MySuperclass';
628 sub setup { ... }
629 sub teardown { ... }
630 # The rest of your Titanium-based follows...
631  
632 It is also possible, within your cgiapp_prerun() method, to change the
633 run mode of your application. This can be done via the prerun_mode()
634 method, which is discussed elsewhere.
635  
636 =head3 cgiapp_postrun()
637  
638 If implemented, this hook will be called after the run mode method
639 has returned its output, but before HTTP headers are generated. This
640 will give you an opportunity to modify the body and headers before they
641 are returned to the web browser.
642  
643 A typical use for this hook is pipelining the output of a CGI-Application
644 through a series of "filter" processors. For example:
645  
646 * You want to enclose the output of all your CGI-Applications in
647 an HTML table in a larger page.
648  
649 * Your run modes return structured data (such as XML), which you
650 want to transform using a standard mechanism (such as XSLT).
651  
652 * You want to post-process CGI-App output through another system,
653 such as HTML::Mason.
654  
655 * You want to modify HTTP headers in a particular way across all
656 run modes, based on particular criteria.
657  
658 The cgiapp_postrun() hook receives a reference to the output from
659 your run mode method, in addition to the CGI-App object. A typical
660 cgiapp_postrun() method might be implemented as follows:
661  
662 sub cgiapp_postrun {
663 my $c = shift;
664 my $output_ref = shift;
665  
666 # Enclose output HTML table
667 my $new_output = "<table border=1>";
668 $new_output .= "<tr><td> Hello, World! </td></tr>";
669 $new_output .= "<tr><td>". $$output_ref ."</td></tr>";
670 $new_output .= "</table>";
671  
672 # Replace old output with new output
673 $$output_ref = $new_output;
674 }
675  
676 Obviously, with access to the CGI-App object you have full access to use all
677 the methods normally available in a run mode. You could, for example, use
678 C<load_tmpl()> to replace the static HTML in this example with
679 L<HTML::Template>. You could change the HTTP headers (via C<header_add()> ).
680 You could also use the objects properties to apply changes only under certain
681 circumstance, such as a in only certain run modes, and when a C<param()> is a
682 particular value.
683  
684 =head3 cgiapp_get_query()
685  
686 my $q = $c->cgiapp_get_query;
687  
688 Override this method to retrieve the query object if you wish to use a
689 different query interface instead of CGI.pm.
690  
691 CGI.pm is only loaded to provided query object is only loaded if it used on a given request.
692  
693 If you can use an alternative to CGI.pm, it needs to have some compatibility
694 with the CGI.pm API. For normal use, just having a compatible C<param> method
695 should be sufficient.
696  
697 If use the C<path_info> option to the mode_param() method, then we will call
698 the C<path_info()> method on the query object.
699  
700 If you use the C<Dump> method in Titanium, we will call the C<Dump> and
701 C<escapeHTML> methods on the query object.
702  
703 =head2 More Application Methods
704  
705 You can skip this section if you are just getting started.
706  
707 The following additional methods are inherited from Titanium, and are
708 available to be called by your application within your Application Module.
709 These functions are listed in alphabetical order.
710  
711 =head3 error_mode()
712  
713 $c->error_mode('my_error_rm');
714  
715 If the runmode dies for whatever reason, C<run() will> see if you have set a
716 value for C<error_mode()>. If you have, C<run()> will call that method
717 as a run mode, passing $@ as the only parameter.
718  
719 No C<error_mode> is defined by default. The death of your C<error_mode()> run
720 mode is not trapped, so you can also use it to die in your own special way.
721  
722 For a complete integrated logging solution, check out L<CGI::Application::Plugin::LogDispatch>.
723  
724 =head3 header_add()
725  
726 # add or replace the 'type' header
727 $c->header_add( -type => 'image/png' );
728  
729 - or -
730  
731 # add an additional cookie
732 $c->header_add(-cookie=>[$extra_cookie]);
733  
734 The C<header_add()> method is used to add one or more headers to the outgoing
735 response headers. The parameters will eventually be passed on to the CGI.pm
736 header() method, so refer to the L<CGI> docs for exact usage details.
737  
738 Unlike calling C<header_props()>, C<header_add()> will preserve any existing
739 headers. If a scalar value is passed to C<header_add()> it will replace
740 the existing value for that key.
741  
742 If an array reference is passed as a value to C<header_add()>, values in
743 that array ref will be appended to any existing values values for that key.
744 This is primarily useful for setting an additional cookie after one has already
745 been set.
746  
747 =head3 header_props()
748  
749 $c->header_props(-type=>'image/gif',-expires=>'+3d');
750  
751 The C<header_props()> method expects a hash of CGI.pm-compatible
752 HTTP header properties. These properties will be passed directly
753 to CGI.pm's C<header()> or C<redirect()> methods. Refer to L<CGI>
754 for exact usage details.
755  
756 Calling header_props any arguments will clobber any existing headers that have
757 previously set.
758  
759 C<header_props()> return a hash of all the headers that have currently been
760 set. It can be called with no arguments just to get the hash current headers
761 back.
762  
763 To add additional headers later without clobbering the old ones,
764 see C<header_add()>.
765  
766 B<IMPORTANT NOTE REGARDING HTTP HEADERS>
767  
768 It is through the C<header_props()> and C<header_add()> method that you may
769 modify the outgoing HTTP headers. This is necessary when you want to set a
770 cookie, set the mime type to something other than "text/html", or perform a
771 redirect. Understanding this relationship is important if you wish to
772 manipulate the HTTP header properly.
773  
774 =head3 redirect()
775  
776 return $c->redirect('http://www.example.com/');
777  
778 Redirect to another URL.
779  
780 =head3 forward()
781  
782 return $c->forward('rm_name');
783  
784 Pass control to another run mode and return its output. This is equivalent to
785 calling $self->$other_runmode, except that the internal value of the current
786 run mode is updated. This bookkeeping is important to load_tmpl() when called
787 with no arguments and some other plugins.
788  
789 =head3 dbh()
790  
791 sub cgiapp_init {
792 my $c = shift;
793
794 # use the same args as DBI->connect();
795 $c->dbh_config($data_source, $username, $auth, \%attr);
796
797 }
798  
799 sub form_process {
800 my $c = shift;
801  
802 my $dbh = $c->dbh;
803 }
804  
805 Easy access to a DBI database handle. The database connection is not created
806 until the first call to C<dbh()>. See L<CGI::Application::Plugin::DBH|CGI::Application::Plugin::DBH> for more
807 features and details.
808  
809 =head3 session()
810  
811 # in cgiapp_init()
812 $c->session_config(
813 CGI_SESSION_OPTIONS => [ "driver:PostgreSQL;serializer:Storable", $self->query, {Handle=>$dbh} ],
814 );
815  
816 # in a run mode
817 my $ses = $c->session->param('foo');
818  
819 Easy access to a L<CGI::Session|CGI::Session> object, so you can store user
820 data between requests. The session is not accessed or created until the first
821 call to session() in a given request. See
822 L<CGI::Application::Plugin::Session|CGI::Application::Plugin::Session> for more
823 features and details.
824  
825 =head3 cfg()
826
827 $c->cfg('root_uri');
828  
829 Easy access to parameters loaded from a config file, which can be stored in one
830 of several formats, including YAML and Pure Perl. For more features and details
831 see
832 L<CGI::Application::Plugin::ConfigAuto|CGI::Application::Plugin::ConfigAuto>.
833  
834 =head3 log()
835  
836 $c->log->info('Information message');
837 $c->log->debug('Debug message');
838  
839 Easy access to a L<Log::Dispatch|Log::Dispatch> logging object, allowing you to log to different
840 locations with different locations of severity. By adjusting the logging level
841 for your application, you make "debug" messages appear or disappear from your logs
842 without making pervasive code changes. See
843 L<CGI::Application::Plugin::LogDispatch|CGI::Application::Plugin::LogDispatch>
844 for more features and details.
845  
846 =head3 check_rm()
847  
848 my ($results, $err_page) = $c->check_rm('form_display','_form_profile');
849 return $err_page if $err_page;
850  
851 Easy form validation with L<Data::FormValidator|Data::FormValidator>. If the
852 validation fails, we'll re-display the form for the user with their data
853 pre-filled and the errors highlighted. You'll have full control over the design
854 of the errors with HTML and CSS in your templates, although we provide some
855 intelligent defaults. See L<CGI::Application::Plugin::ValidateRM|CGI::Application::Plugin::ValidateRM> for features and details.
856  
857 =head3 fill_form()
858  
859 # fill an HTML form with data in a hashref or from an object with with a param() method
860 my $filled_html = $self->fill_form($html, $data);
861  
862 # ...or default to getting data from $self->query()
863 my $filled_html = $self->fill_form($html);
864  
865 HTML::FillInForm is a useful when you want to fill in a web form with default
866 values from a database table. Like many CPAN modules, you can use directly from
867 CGI::Application without any special plugin. The value of this plugin is that
868 it defaults to finding values through $self->query(). Besides that, it is just
869 a bit of synatic sugar that was mostly created work-around weaknesses in the
870 HTML::FillInForm 1.x interface, which were fixed with HTML::FillInForm 2.0
871 release. See L<CGI::Application::Plugin::FillInForm|CGI::Application::Plugin::FillInForm>
872 for details.
873  
874 =head3 error()
875  
876 $c->error( title => '..', msg => '..' );
877  
878 Provide quick error messages back to the user for exceptional cases. You can
879 provide your own custom designed template or use the default one built-in. See
880 L<CGI::Application::Plugin::ErrorPage|CGI::Application::Plugin::ErrorPage>.
881  
882 =head3 stream_file()
883  
884 $c->stream_file($file);
885
886 If your run mode is outputing an image or a spreadsheet instead of an HTML
887 page, you may want to stream the output. This method takes care of the boring
888 details of buffering, headers and MIME types. See
889 L<CGI::Application::Plugin::Stream|CGI::Application::Plugin::Stream> for
890 details.
891  
892 =head3 prerun_mode()
893  
894 $c->prerun_mode('new_run_mode');
895  
896 The prerun_mode() method is an accessor/mutator which can be used within
897 your cgiapp_prerun() method to change the run mode which is about to be executed.
898 For example, consider:
899  
900 # In WebApp.pm:
901 package WebApp;
902 use base 'Titanium';
903 sub cgiapp_prerun {
904 my $c = shift;
905  
906 # Get the web user name, if any
907 my $q = $c->query();
908 my $user = $q->remote_user();
909  
910 # Redirect to login, if necessary
911 unless ($user) {
912 $c->prerun_mode('login');
913 }
914 }
915  
916 In this example, the web user will be forced into the "login" run mode
917 unless they have already logged in. The prerun_mode() method permits
918 a scalar text string to be set which overrides whatever the run mode
919 would otherwise be.
920  
921 The prerun_mode() method should be used in cases where you want to use
922 Titanium's normal run mode switching facility, but you want to make selective
923 changes to the mode under specific conditions.
924  
925 B<Note:> The prerun_mode() method may ONLY be called in the context of
926 a cgiapp_prerun() method. Your application will die() if you call
927 prerun_mode() elsewhere, such as in setup() or a run mode method.
928  
929 =head2 Dispatching Clean URIs to run modes
930  
931 Modern web frameworks dispense with cruft in URIs, providing in clean
932 URIs instead. Instead of:
933  
934 /cgi-bin/item.cgi?rm=view&id=15
935  
936 A clean URI to describe the same resource might be:
937  
938 /item/15/view
939  
940 The process of mapping these URIs to run modes is called dispatching and is
941 handled by L<CGI::Application::Dispatch|CGI::Application::Dispatch>.
942 Dispatching is not required and is a layer you can fairly easily add to an
943 application later.
944  
945 =head2 Offline website development
946  
947 You can work on your Titanium project on your desktop or laptop without
948 installing a full-featured web-server like Apache. Instead, install
949 L<CGI::Application::Server|CGI::Application::Server> from CPAN. After a few
950 minutes of setup, you'll have your own private application server up and
951 running.
952  
953 =head2 Automated Testing
954  
955 There a couple of testing modules specifically made for Titanium.
956  
957 L<Test::WWW::Mechanize::CGIApp|Test::WWW::Mechanize::CGIApp> allows functional
958 testing of a CGI::App-based project without starting a web server.
959 L<Test::WWW::Mechanize|Test::WWW::Mechanize> could be used to test the app
960 through a real web server.
961  
962 L<Test::WWW::Selenium|Test::WWW::Selenium::CGIApp> is similar, but uses
963 Selenium for the testing, meaning that a local web-browser would be used,
964 allowing testing of websites that contain JavaScript.
965  
966 Direct testing is also easy. Titanium will normally print the output of it's
967 run modes directly to STDOUT. This can be surprised with an enviroment variable,
968 CGI_APP_RETURN_ONLY. For example:
969  
970 $ENV{CGI_APP_RETURN_ONLY} = 1;
971 $output = $c->run;
972 like($output, qr/good/, "output is good");
973  
974 Examples of this style can be seen in our own test suite.
975  
976 =head1 PLUGINS
977  
978 Titanium has a plug-in architecture that is easy to use and easy to develop new
979 plug-ins for. Plugins made for CGI::Application are directly compatible. The
980 CGI::Application should be referenced for those who wish to write plugins.
981  
982 Select plugins are listed below. For a current complete list, please consult
983 CPAN:
984  
985 http://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin
986  
987 =over 4
988  
989 =item *
990  
991 L<CGI::Application::Plugin::Apache|CGI::Application::Plugin::Apache> - Use Apache::* modules without interference
992  
993 =item *
994  
995 L<CGI::Application::Plugin::AutoRunmode|CGI::Application::Plugin::AutoRunmode> - Automatically register runmodes
996  
997 =item *
998  
999 L<CGI::Application::Plugin::CompressGzip|CGI::Application::Plugin::CompressGzip> - Add Gzip compression
1000  
1001 =item *
1002  
1003 L<CGI::Application::Plugin::TT|CGI::Application::Plugin::TT> - Use L<Template::Toolkit|Template::Toolkit> as an alternative to HTML::Template.
1004  
1005  
1006 =back
1007  
1008 Consult each plug-in for the exact usage syntax.
1009  
1010 =head1 COMMUNITY
1011  
1012 Therese are primary resources available for those who wish to learn more
1013 about Titanium and discuss it with others.
1014  
1015 B<Wiki>
1016  
1017 This is a community built and maintained resource that anyone is welcome to
1018 contribute to. It contains a number of articles of its own and links
1019 to many other Titanium related pages. It is currently branded as CGI::Application,
1020 but the code is the same.
1021  
1022 L<http://www.cgi-app.org>
1023  
1024 B<Support Mailing List>
1025  
1026 If you have any questions, comments, bug reports or feature suggestions,
1027 post them to the support mailing list! To join the mailing list, simply
1028 send a blank message to "cgiapp-subscribe@lists.erlbaum.net".
1029  
1030 B<IRC>
1031  
1032 You can also drop by C<#cgiapp> on C<irc.perl.org> with a good chance of finding
1033 some people involved with the project there.
1034  
1035 B<Source Code>
1036  
1037 This project is managed using the darcs source control system (
1038 http://www.darcs.net/ ). The darcs archive is here:
1039 http://mark.stosberg.com/darcs_hive/titanium
1040  
1041 =head1 TODO
1042  
1043 * I would like Titanium to be easier to install and get started with. Rather
1044 than depending on the large CPAN dependency chain being installed, I would like
1045 an option for users to download the full stack of dependencies, so that you can
1046 just unpack a single file and go.
1047  
1048 * I'd like a plugin to cope with the URI-encoding that Dreamweaver does to templates
1049 that may just mean packing and releasing the following code as a plug-in:
1050  
1051 CGI::Application->add_callback('load_tmpl',sub {
1052 my ($c, $ht_params, $tmpl_params, $tmpl_file) = @_;
1053
1054 require HTML::Template::Filter::URIdecode;
1055 import HTML::Template::Filter::URIdecode 'ht_uri_decode';
1056
1057 # If you already have a filter defined, don't do anything.
1058 # If you want to add more of your own filters later, be mindful
1059 # about whether you add to this arrayref, or replace it.
1060 unless ($ht_params->{filter}) {
1061 $ht_params->{filter} = [\&ht_uri_decode]
1062 }
1063 });
1064
1065  
1066  
1067 =head1 SEE ALSO
1068  
1069 =over 4
1070  
1071 =item *
1072  
1073 L<CGI::Application|CGI::Application>
1074  
1075 =back
1076  
1077 =head1 MORE READING
1078  
1079 If you're interested in finding out more about Titanium, the
1080 following articles are available on Perl.com, providing
1081 context about the underlying CGI::Application framework
1082  
1083 Using CGI::Application
1084 http://www.perl.com/pub/a/2001/06/05/cgi.html
1085  
1086 Rapid Website Development with CGI::Application
1087 http://www.perl.com/pub/a/2006/10/19/cgi_application.html
1088  
1089 Thanks to O'Reilly for publishing these articles, and for the incredible value
1090 they provide to the Perl community!
1091  
1092 =head1 AUTHORS
1093  
1094 Many.
1095  
1096 Mark Stosberg, C<< mark@summersault.com >> published the original Titanium module,
1097 while many another contributed to CGI::Application and the related plugins.
1098  
1099 =head1 LICENSE
1100  
1101 Copyright (C) 2008, Mark Stosberg.
1102  
1103 This module is free software; you can redistribute it and/or modify it under
1104 the terms of either:
1105  
1106 a) the GNU General Public License as published by the Free Software
1107 Foundation; either version 1, or (at your option) any later version,
1108  
1109 or
1110  
1111 b) the "Artistic License".
1112  
1113 This program is distributed in the hope that it will be useful,
1114 but WITHOUT ANY WARRANTY; without even the implied warranty of
1115 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either
1116 the GNU General Public License or the Artistic License for more details.
1117  
1118 =cut
1119  
1120 1;