Debian Codegraph @

README

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