.\" Automatically generated by Pod::Man 4.11 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "Titanium 3pm" .TH Titanium 3pm "2020-08-22" "perl v5.30.3" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Titanium \- A strong, lightweight web application framework .SH "SYNOPSIS" .IX Header "SYNOPSIS" .SS "Coding" .IX Subsection "Coding" .Vb 3 \& # In "WebApp.pm"... \& package WebApp; \& use base \*(AqTitanium\*(Aq; \& \& sub setup { \& my $c = shift; \& \& $c\->start_mode(\*(Aqform_display\*(Aq); \& $c\->run_modes([qw/ \& form_display \& form_process \& /]); \& } \& sub form_display { \& my $c = shift; \& my $errs = shift; \& \& my $t = $c\->load_tmpl; \& $t\->param($errs) if $errs; \& return $t\->output; \& } \& sub form_process { \& my $c = shift; \& \& # Validate the form against a profile. If it fails validation, re\-display \& # the form for the user with their data pre\-filled and the errors highlighted. \& my ($results, $err_page) = $c\->check_rm(\*(Aqform_display\*(Aq,\*(Aq_form_profile\*(Aq); \& return $err_page if $err_page; \& \& return $c\->forward(\*(Aqform_success\*(Aq); \& } \& \& # Return a Data::FormValidator profile \& sub _form_profile { \& my $c = shift; \& return { \& required => \*(Aqemail\*(Aq, \& }; \& } \& \& sub form_success { ... } \& \& 1; \& \& ### In "webapp.cgi"... \& use WebApp; \& my $c = WebApp\->new(); \& $c\->run(); .Ve .PP Inside the run modes, the following methods are available: .PP .Vb 10 \& $c\->query; # A query object. CGI.pm by default. \& $c\->redirect(\*(Aqhttp://othersite.com\*(Aq); # Basic redirection \& $c\->dbh; # DBI database handle \& $c\->session(); # A CGI::Session object \& $c\->check_rm; # Form validation with Data::FormValidator \& $c\->cfg(\*(Aqroot_uri\*(Aq); # Config file access (YAML, Perl or INI formats) \& $c\->fill_form; # Form filling with HTML::FillInForm \& $c\->error( title => \*(Aq..\*(Aq, msg => \*(Aq..\*(Aq ); # Easy error page generation \& $c\->stream_file($file); # file streaming \& $c\->log; # A Log::Dispatch object .Ve .SS "Development and Testing" .IX Subsection "Development and Testing" Easily setup the project skeleton using the bundled cgiapp-starter script. .PP In development you can turn on a debugging screen and a developer pop-up to quickly catch code, html and performance issues, thanks to CGI::Application::Plugin::DebugScreen and CGI::Application::Plugin::DevPopup. .PP For automated testing, Test::WWW::Mechanize::CGIApp is bundled, allowing you to functionally test your web application without involving a full web server. If you'd rather test against full web server, Test::WWW::Mechanize is there, too. .SS "Dispatching with Clean URIs" .IX Subsection "Dispatching with Clean URIs" Modern web frameworks dispense with cruft in URIs. Instead of: .PP .Vb 1 \& /cgi\-bin/item.cgi?rm=view&id=15 .Ve .PP A clean \s-1URI\s0 to describe the same resource might be: .PP .Vb 1 \& /item/15/view .Ve .PP The process of mapping these URIs to run modes is called dispatching and is handled by CGI::Application::Dispatch. It comes with a default dispatch table that automatically creates URLs in this pattern for you: .PP .Vb 1 \& /app/module_name/run_mode .Ve .PP There's plenty of flexibility to design your own URIs if you'd like. .SH "Elements of Titanium" .IX Header "Elements of Titanium" * \fBTitanium is solid and mature\fR. While it has a new name, the reality is that Titanium is simply a more user-friendly packaging of the mature CGI::Application framework and some useful plugins. These packages have already been refined and vetted. The seed framework was first released in 2000 and by 2005 was mature. Titanium contains no real code of its own, and there is no intention to do so in the future. Instead, we may select other mature plugins to include in the future. Other \*(L"Titanium alloys\*(R" in the \*(L"Titanium::Alloy::\*(R" name space may also come to exist, following the same philosophy, but choosing to bundle a different combination of plugins. .PP * \fBTitanium is lightweight\fR. Titanium has a very light core and the plugins it uses employ lazy-loading whenever possible. That means that while we have built-in database plugin, we don't have to load \s-1DBI\s0 or make a database connection until you actually use the database connection. Titanium runs well in a plain \s-1CGI\s0 environment and provides excellent performance in a persistent environment such as FastCGI or mod_perl. Titanium apps are compatible with the dozens of published plugins for CGI::Application, so you can add additional features as your needs evolve. .SH "DESCRIPTION" .IX Header "DESCRIPTION" It is intended that your Application Module will be implemented as a sub-class of Titanium. This is done simply as follows: .PP .Vb 2 \& package My::App; \& use base \*(AqTitanium\*(Aq; .Ve .PP \&\fBNotation and Conventions\fR .PP For the purpose of this document, we will refer to the following conventions: .PP .Vb 6 \& WebApp.pm : The Perl module which implements your Application Module class. \& WebApp : Your Application Module class; a sub\-class of Titanium. \& webapp.cgi : The Instance Script which implements your Application Module. \& $c : Used in instance methods to pass around the \& current object. (Sometimes referred as "$self" in other projects.) \& Think of the "$c" as short for "controller". .Ve .SS "Script/Dispatching Methods" .IX Subsection "Script/Dispatching Methods" By inheriting from Titanium you have access to a number of built-in methods. The following are those which are expected to be called from your Instance Script or through your CGI::Application::Dispatch dispatcher. .PP \fI\f(BInew()\fI\fR .IX Subsection "new()" .PP The \fBnew()\fR method is the constructor for a Titanium. It returns a blessed reference to your Application Module class. Optionally, \&\fBnew()\fR may take a set of parameters as key => value pairs: .PP .Vb 7 \& my $c = WebApp\->new( \& TMPL_PATH => \*(AqApp/\*(Aq, \& PARAMS => { \& \*(Aqcustom_thing_1\*(Aq => \*(Aqsome val\*(Aq, \& \*(Aqanother_custom_thing\*(Aq => [qw/123 456/] \& } \& ); .Ve .PP This method may take some specific parameters: .PP \&\fB\s-1TMPL_PATH\s0\fR \- This optional parameter defines a path to a directory of templates. This is used by the \fBload_tmpl()\fR method (specified below), and may also be used for the same purpose by other template plugins. This run-time parameter allows you to further encapsulate instantiating templates, providing potential for more re-usability. It can be either a scalar or an array reference of multiple paths. .PP \&\fB\s-1QUERY\s0\fR \- This optional parameter allows you to specify an already-created \s-1CGI\s0 query object. Under normal use, Titanium will instantiate its own \&\s-1CGI\s0.pm query object. Under certain conditions, it might be useful to be able to use one which has already been created. .PP \&\fB\s-1PARAMS\s0\fR \- This parameter, if used, allows you to set a number of custom parameters at run-time. By passing in different values in different instance scripts which use the same application module you can achieve a higher level of re-usability. For instance, imagine an application module, \*(L"Mailform.pm\*(R". The application takes the contents of a \s-1HTML\s0 form and emails it to a specified recipient. You could have multiple instance scripts throughout your site which all use this \*(L"Mailform.pm\*(R" module, but which set different recipients or different forms. .PP One common use of instance scripts is to provide a path to a config file. This design allows you to define project wide configuration objects used by many several instance scripts. There are several plugins which simplify the syntax for this and provide lazy loading. Here's an example using CGI::Application::Plugin::ConfigAuto, which uses Config::Auto to support many configuration file formats. .PP .Vb 1 \& my $app = WebApp\->new(PARAMS => { cfg_file => \*(Aqconfig.pl\*(Aq }); \& \& # Later in your app: \& my %cfg = $c\->cfg() \& # or ... $c\->cfg(\*(AqHTML_ROOT_DIR\*(Aq); .Ve .PP See the list of of plugins below for more config file integration solutions. .PP \fI\f(BIrun()\fI\fR .IX Subsection "run()" .PP The \fBrun()\fR method is called upon your Application Module object, from your Instance Script. When called, it executes the functionality in your Application Module. .PP .Vb 2 \& my $c = WebApp\->new; \& $c\->run; .Ve .PP This method determines the application state by looking at the dispatch table, as described in CGI::Application::Dispatch. .PP Once the mode has been determined, \fBrun()\fR looks at the hash stored in \&\fBrun_modes()\fR and finds the subroutine which is tied to a specific hash key. If found, the function is called and the data returned is \fBprint()\fR'ed to \s-1STDOUT\s0 and to the browser. If the specified mode is not found in the \fBrun_modes()\fR table, \&\fBrun()\fR will \fBcroak()\fR. This 'death' can possibly be captured and handled using \f(CW\*(C`error_mode()\*(C'\fR, described below. .SS "Essential Method to Override" .IX Subsection "Essential Method to Override" Titanium implements some methods which are expected to be overridden by implementing them in your sub-class module. One of these is essential to do: .PP \fI\f(BIsetup()\fI\fR .IX Subsection "setup()" .PP This method is called by the inherited \fBnew()\fR constructor method. The \&\fBsetup()\fR method should be used to define the following property/methods: .PP .Vb 2 \& start_mode() \- string containing the default run mode. \& run_modes() \- hash table containing mode => function mappings. \& \& error_mode() \- string containing the error mode. \& tmpl_path() \- string or array reference containing path(s) to template directories. .Ve .PP Your \fBsetup()\fR method may call any of the instance methods of your application. This function is a good place to define properties specific to your application via the \f(CW$c\fR\->\fBparam()\fR method. .PP Your \fBsetup()\fR method might be implemented something like this: .PP .Vb 8 \& sub setup { \& my $c = shift; \& $c\->start_mode(\*(Aqputform\*(Aq); \& $c\->run_modes([qw/ \& form \& form_process \& /]); \& } .Ve .SS "Essential Application Methods" .IX Subsection "Essential Application Methods" The following methods are inherited from Titanium, and are available to be called by your application within your Application Module. They are called essential because you will use all are most of them to get any application up and running. These functions are listed in alphabetical order. .PP \fI\f(BIload_tmpl()\fI\fR .IX Subsection "load_tmpl()" .PP .Vb 4 \& my $tmpl_obj = $c\->load_tmpl; \& my $tmpl_obj = $c\->load_tmpl(\*(Aqsome.html\*(Aq); \& my $tmpl_obj = $c\->load_tmpl( \e$template_content ); \& my $tmpl_obj = $c\->load_tmpl( FILEHANDLE ); .Ve .PP This method takes the name of a template file, a reference to template data or a \s-1FILEHANDLE\s0 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 \*(L".html\*(R". .PP If you use the default template naming system, you should also use CGI::Application::Plugin::Forward, which simply helps to keep the current name accurate when you pass control from one run mode to another. .PP ( For integration with other template systems and automated template names, see "Alternatives to \fBload_tmpl()\fR below. ) .PP When you pass in a filename, the HTML::Template\->\fBnew_file()\fR constructor is used for create the object. When you pass in a reference to the template content, the HTML::Template\->\fBnew_scalar_ref()\fR constructor is used and when you pass in a filehandle, the HTML::Template\->\fBnew_filehandle()\fR constructor is used. .PP Refer to HTML::Template for specific usage of HTML::Template. .PP If \fBtmpl_path()\fR has been specified, \fBload_tmpl()\fR will set the HTML::Template \f(CW\*(C`path\*(C'\fR option to the path(s) provided. This further assists in encapsulating template usage. .PP The \fBload_tmpl()\fR method will pass any extra parameters sent to it directly to HTML::Template\->\fBnew_file()\fR (or \fBnew_scalar_ref()\fR or \fBnew_filehandle()\fR). This will allow the HTML::Template object to be further customized: .PP .Vb 4 \& my $tmpl_obj = $c\->load_tmpl(\*(Aqsome_other.html\*(Aq, \& die_on_bad_params => 0, \& cache => 1 \& ); .Ve .PP Note that if you want to pass extra arguments but use the default template name, you still need to provide a name of \f(CW\*(C`undef\*(C'\fR: .PP .Vb 4 \& my $tmpl_obj = $c\->load_tmpl(undef\*(Aq, \& die_on_bad_params => 0, \& cache => 1 \& ); .Ve .PP \&\fBAlternatives to \fBload_tmpl()\fB\fR .PP If your application requires more specialized behavior than this, you can always replace it by overriding \fBload_tmpl()\fR by implementing your own \&\fBload_tmpl()\fR in your Titanium sub-class application module. .PP First, you may want to check out the template related plugins. .PP CGI::Application::Plugin::TT focuses just on Template Toolkit integration, and features pre-and-post features, singleton support and more. .PP \fI\f(BIparam()\fI\fR .IX Subsection "param()" .PP .Vb 1 \& $c\->param(\*(Aqpname\*(Aq, $somevalue); .Ve .PP The \fBparam()\fR method provides a facility through which you may set application instance properties which are accessible throughout your application. .PP The \fBparam()\fR method may be used in two basic ways. First, you may use it to get or set the value of a parameter: .PP .Vb 2 \& $c\->param(\*(Aqscalar_param\*(Aq, \*(Aq123\*(Aq); \& my $scalar_param_values = $c\->param(\*(Aqsome_param\*(Aq); .Ve .PP Second, when called in the context of an array, with no parameter name specified, \fBparam()\fR returns an array containing all the parameters which currently exist: .PP .Vb 1 \& my @all_params = $c\->param(); .Ve .PP The \fBparam()\fR method also allows you to set a bunch of parameters at once by passing in a hash (or hashref): .PP .Vb 5 \& $c\->param( \& \*(Aqkey1\*(Aq => \*(Aqval1\*(Aq, \& \*(Aqkey2\*(Aq => \*(Aqval2\*(Aq, \& \*(Aqkey3\*(Aq => \*(Aqval3\*(Aq, \& ); .Ve .PP The \fBparam()\fR method enables a very valuable system for customizing your applications on a per-instance basis. One Application Module might be instantiated by different Instance Scripts. Each Instance Script might set different values for a set of parameters. This allows similar applications to share a common code-base, but behave differently. For example, imagine a mail form application with a single Application Module, but multiple Instance Scripts. Each Instance Script might specify a different recipient. Another example would be a web bulletin boards system. There could be multiple boards, each with a different topic and set of administrators. .PP The \fBnew()\fR method provides a shortcut for specifying a number of run-time parameters at once. Internally, Titanium calls the \fBparam()\fR method to set these properties. The \fBparam()\fR method is a powerful tool for greatly increasing your application's re-usability. .PP \fI\f(BIquery()\fI\fR .IX Subsection "query()" .PP .Vb 2 \& my $q = $c\->query(); \& my $remote_user = $q\->remote_user(); .Ve .PP This method retrieves the \s-1CGI\s0.pm query object which has been created by instantiating your Application Module. For details on usage of this query object, refer to \s-1CGI\s0. Titanium is built on the \s-1CGI\s0 module. Generally speaking, you will want to become very familiar with \s-1CGI\s0.pm, as you will use the query object whenever you want to interact with form data. .PP When the \fBnew()\fR method is called, a \s-1CGI\s0 query object is automatically created. If, for some reason, you want to use your own \s-1CGI\s0 query object, the \fBnew()\fR method supports passing in your existing query object on construction using the \s-1QUERY\s0 attribute. .PP \fI\f(BIrun_modes()\fI\fR .IX Subsection "run_modes()" .PP .Vb 5 \& # The common usage: an arrayref of run mode names that exactly match subroutine names \& $c\->run_modes([qw/ \& form_display \& form_process \& /]); \& \& # With a hashref, use a different name or a code ref \& $c\->run_modes( \& \*(Aqmode1\*(Aq => \*(Aqsome_sub_by_name\*(Aq, \& \*(Aqmode2\*(Aq => \e&some_other_sub_by_ref \& ); .Ve .PP This accessor/mutator specifies a lookup table for the application states, using the syntax examples above. It returns the dispatch table as a hash. .PP The \fBrun_modes()\fR method may be called more than once. Additional values passed into \fBrun_modes()\fR will be added to the run modes table. In the case that an existing run mode is re-defined, the new value will override the existing value. This behavior might be useful for applications which are created via inheritance from another application, or some advanced application which modifies its own capabilities based on user input. .PP The \fBrun()\fR method uses the data in this table to send the application to the correct function as determined by the dispatcher, as described in CGI::Application::Dispatch. These functions are referred to as \*(L"run mode methods\*(R". .PP The hash table set by this method is expected to contain the mode name as a key. The value should be either a hard reference (a subref) to the run mode method which you want to be called when the application enters the specified run mode, or the name of the run mode method to be called: .PP .Vb 2 \& \*(Aqmode_name_by_ref\*(Aq => \e&mode_function \& \*(Aqmode_name_by_name\*(Aq => \*(Aqmode_function\*(Aq .Ve .PP The run mode method specified is expected to return a block of text (e.g.: \&\s-1HTML\s0) which will eventually be sent back to the web browser. The run mode method may return its block of text as a scalar or a scalar-ref. .PP An advantage of specifying your run mode methods by name instead of by reference is that you can more easily create derivative applications using inheritance. For instance, if you have a new application which is exactly the same as an existing application with the exception of one run mode, you could simply inherit from that other application and override the run mode method which is different. If you specified your run mode method by reference, your child class would still use the function from the parent class. .PP An advantage of specifying your run mode methods by reference instead of by name is performance. Dereferencing a subref is faster than \fBeval()\fR\-ing a code block. If run-time performance is a critical issue, specify your run mode methods by reference and not by name. The speed differences are generally small, however, so specifying by name is preferred. .PP Specifying the run modes by array reference: .PP .Vb 1 \& $c\->run_modes([ \*(Aqmode1\*(Aq, \*(Aqmode2\*(Aq, \*(Aqmode3\*(Aq ]); .Ve .PP Is is the same as using a hash, with keys equal to values .PP .Vb 5 \& $c\->run_modes( \& \*(Aqmode1\*(Aq => \*(Aqmode1\*(Aq, \& \*(Aqmode2\*(Aq => \*(Aqmode2\*(Aq, \& \*(Aqmode3\*(Aq => \*(Aqmode3\*(Aq \& ); .Ve .PP Often, it makes good organizational sense to have your run modes map to methods of the same name. The array-ref interface provides a shortcut to that behavior while reducing verbosity of your code. .PP Note that another importance of specifying your run modes in either a hash or array-ref is to assure that only those Perl methods which are specifically designated may be called via your application. Application environments which don't specify allowed methods and disallow all others are insecure, potentially opening the door to allowing execution of arbitrary code. Titanium maintains a strict \*(L"default-deny\*(R" stance on all method invocation, thereby allowing secure applications to be built upon it. .PP \&\fB\s-1IMPORTANT NOTE ABOUT RUN MODE METHODS\s0\fR .PP Your application should *NEVER* \fBprint()\fR to \s-1STDOUT.\s0 Using \fBprint()\fR to send output to \s-1STDOUT\s0 (including \s-1HTTP\s0 headers) is exclusively the domain of the inherited \fBrun()\fR method. Breaking this rule is a common source of errors. If your program is erroneously sending content before your \s-1HTTP\s0 header, you are probably breaking this rule. .PP \&\fB\s-1THE RUN MODE OF LAST RESORT: \*(L"AUTOLOAD\*(R"\s0\fR .PP If Titanium is asked to go to a run mode which doesn't exist, by default it will return an error page to the user, implemented like this: .PP .Vb 4 \& return $c\->error( \& title => \*(AqThe requested page was not found.\*(Aq, \& msg => "(The page tried was: ".$c\->get_current_runmode.")" \& ); .Ve .PP See CGI::Application::Plugin::ErrorPage for more details on the built-in error page system. If this is not your desired behavior for handling unknown run mode requests, implement your own run mode with the reserved name \&\*(L"\s-1AUTOLOAD\*(R":\s0 .PP .Vb 3 \& $c\->run_modes( \& "AUTOLOAD" => \e&catch_my_exception \& ); .Ve .PP Before Titanium invokes its own error page handling it will check for the existence of a run mode called \*(L"\s-1AUTOLOAD\*(R".\s0 If specified, this run mode will in invoked just like a regular run mode, with one exception: It will receive, as an argument, the name of the run mode which invoked it: .PP .Vb 3 \& sub catch_my_exception { \& my $c = shift; \& my $intended_runmode = shift; \& \& my $output = "Looking for \*(Aq$intended_runmode\*(Aq, but found \*(AqAUTOLOAD\*(Aq instead"; \& return $output; \& } .Ve .PP This functionality could be for more sophisticated application behaviors. .PP \fI\f(BIstart_mode()\fI\fR .IX Subsection "start_mode()" .PP .Vb 1 \& $c\->start_mode(\*(Aqmode1\*(Aq); .Ve .PP The start_mode contains the name of the mode as specified in the \fBrun_modes()\fR table. Default mode is \*(L"start\*(R". The mode key specified here will be used whenever the value of the \s-1CGI\s0 form parameter specified by \fBmode_param()\fR is not defined. Generally, this is the first time your application is executed. .PP \fI\f(BItmpl_path()\fI\fR .IX Subsection "tmpl_path()" .PP .Vb 1 \& $c\->tmpl_path(\*(Aq/path/to/some/templates/\*(Aq); .Ve .PP This access/mutator method sets the file path to the directory (or directories) where the templates are stored. It is used by \fBload_tmpl()\fR to find the template files, using HTML::Template's \f(CW\*(C`path\*(C'\fR option. To set the path you can either pass in a text scalar or an array reference of multiple paths. .SS "More Methods to override" .IX Subsection "More Methods to override" Several more non-essential methods are useful to declare in your application class, or in a project \*(L"super class\*(R" that inherits from your Titanium only to serve in turn as a base class for project modules. These additional methods are as follows: .PP \fI\f(BIteardown()\fI\fR .IX Subsection "teardown()" .PP If implemented, this method is called automatically after your application runs. It can be used to clean up after your operations. A typical use of the \&\fBteardown()\fR function is to disconnect a database connection which was established in the \fBsetup()\fR function, or flush open session data. You could also use the \fBteardown()\fR method to store state information about the application to the server. .PP \fI\f(BIcgiapp_init()\fI\fR .IX Subsection "cgiapp_init()" .PP If implemented, this method is called automatically right before the \fBsetup()\fR method is called. The \fBcgiapp_init()\fR method receives, as its parameters, all the arguments which were sent to the \fBnew()\fR method. .PP An example of the benefits provided by utilizing this hook is creating a custom \*(L"application super-class\*(R" from which which all your web applications would inherit, instead of directly from Titanium. .PP Consider the following: .PP .Vb 8 \& # In MySuperclass.pm: \& package MySuperclass; \& use base \*(AqTitanium\*(Aq; \& sub cgiapp_init { \& my $c = shift; \& # Perform some project\-specific init behavior \& # such as to load settings from a database or file. \& } \& \& \& # In MyApplication.pm: \& package MyApplication; \& use base \*(AqMySuperclass\*(Aq; \& sub setup { ... } \& sub teardown { ... } \& # The rest of your Titanium\-based follows... .Ve .PP By using Titanium and the \fBcgiapp_init()\fR method as illustrated, a suite of applications could be designed to share certain characteristics, creating cleaner code. .PP \fI\f(BIcgiapp_prerun()\fI\fR .IX Subsection "cgiapp_prerun()" .PP If implemented, this method is called automatically right before the selected run mode method is called. This method provides an optional pre-runmode hook, which permits functionality to be added at the point right before the run mode method is called. The value of the run mode is passed into \fBcgiapp_prerun()\fR. .PP This could be used by a custom \*(L"application super-class\*(R" from which all your web applications would inherit, instead of Titanium. .PP Consider the following: .PP .Vb 9 \& # In MySuperclass.pm: \& package MySuperclass; \& use base \*(AqTitanium\*(Aq; \& sub cgiapp_prerun { \& my $c = shift; \& # Perform some project\-specific init behavior \& # such as to implement run mode specific \& # authorization functions. \& } \& \& \& # In MyApplication.pm: \& package MyApplication; \& use base \*(AqMySuperclass\*(Aq; \& sub setup { ... } \& sub teardown { ... } \& # The rest of your Titanium\-based follows... .Ve .PP It is also possible, within your \fBcgiapp_prerun()\fR method, to change the run mode of your application. This can be done via the \fBprerun_mode()\fR method, which is discussed elsewhere. .PP \fI\f(BIcgiapp_postrun()\fI\fR .IX Subsection "cgiapp_postrun()" .PP If implemented, this hook will be called after the run mode method has returned its output, but before \s-1HTTP\s0 headers are generated. This will give you an opportunity to modify the body and headers before they are returned to the web browser. .PP A typical use for this hook is pipelining the output of a CGI-Application through a series of \*(L"filter\*(R" processors. For example: .PP .Vb 2 \& * You want to enclose the output of all your CGI\-Applications in \& an HTML table in a larger page. \& \& * Your run modes return structured data (such as XML), which you \& want to transform using a standard mechanism (such as XSLT). \& \& * You want to post\-process CGI\-App output through another system, \& such as HTML::Mason. \& \& * You want to modify HTTP headers in a particular way across all \& run modes, based on particular criteria. .Ve .PP The \fBcgiapp_postrun()\fR hook receives a reference to the output from your run mode method, in addition to the CGI-App object. A typical \&\fBcgiapp_postrun()\fR method might be implemented as follows: .PP .Vb 3 \& sub cgiapp_postrun { \& my $c = shift; \& my $output_ref = shift; \& \& # Enclose output HTML table \& my $new_output = ""; \& $new_output .= ""; \& $new_output .= ""; \& $new_output .= "
Hello, World!
". $$output_ref ."
"; \& \& # Replace old output with new output \& $$output_ref = $new_output; \& } .Ve .PP Obviously, with access to the CGI-App object you have full access to use all the methods normally available in a run mode. You could, for example, use \&\f(CW\*(C`load_tmpl()\*(C'\fR to replace the static \s-1HTML\s0 in this example with HTML::Template. You could change the \s-1HTTP\s0 headers (via \f(CW\*(C`header_add()\*(C'\fR ). You could also use the objects properties to apply changes only under certain circumstance, such as a in only certain run modes, and when a \f(CW\*(C`param()\*(C'\fR is a particular value. .PP \fI\f(BIcgiapp_get_query()\fI\fR .IX Subsection "cgiapp_get_query()" .PP .Vb 1 \& my $q = $c\->cgiapp_get_query; .Ve .PP Override this method to retrieve the query object if you wish to use a different query interface instead of \s-1CGI\s0.pm. .PP \&\s-1CGI\s0.pm is only loaded to provided query object is only loaded if it used on a given request. .PP If you can use an alternative to \s-1CGI\s0.pm, it needs to have some compatibility with the \s-1CGI\s0.pm \s-1API.\s0 For normal use, just having a compatible \f(CW\*(C`param\*(C'\fR method should be sufficient. .PP If use the \f(CW\*(C`path_info\*(C'\fR option to the \fBmode_param()\fR method, then we will call the \f(CW\*(C`path_info()\*(C'\fR method on the query object. .PP If you use the \f(CW\*(C`Dump\*(C'\fR method in Titanium, we will call the \f(CW\*(C`Dump\*(C'\fR and \&\f(CW\*(C`escapeHTML\*(C'\fR methods on the query object. .SS "More Application Methods" .IX Subsection "More Application Methods" You can skip this section if you are just getting started. .PP The following additional methods are inherited from Titanium, and are available to be called by your application within your Application Module. These functions are listed in alphabetical order. .PP \fI\f(BIerror_mode()\fI\fR .IX Subsection "error_mode()" .PP .Vb 1 \& $c\->error_mode(\*(Aqmy_error_rm\*(Aq); .Ve .PP If the runmode dies for whatever reason, \f(CW\*(C`run() will\*(C'\fR see if you have set a value for \f(CW\*(C`error_mode()\*(C'\fR. If you have, \f(CW\*(C`run()\*(C'\fR will call that method as a run mode, passing $@ as the only parameter. .PP No \f(CW\*(C`error_mode\*(C'\fR is defined by default. The death of your \f(CW\*(C`error_mode()\*(C'\fR run mode is not trapped, so you can also use it to die in your own special way. .PP For a complete integrated logging solution, check out CGI::Application::Plugin::LogDispatch. .PP \fI\f(BIheader_add()\fI\fR .IX Subsection "header_add()" .PP .Vb 2 \& # add or replace the \*(Aqtype\*(Aq header \& $c\->header_add( \-type => \*(Aqimage/png\*(Aq ); \& \& \- or \- \& \& # add an additional cookie \& $c\->header_add(\-cookie=>[$extra_cookie]); .Ve .PP The \f(CW\*(C`header_add()\*(C'\fR method is used to add one or more headers to the outgoing response headers. The parameters will eventually be passed on to the \s-1CGI\s0.pm \&\fBheader()\fR method, so refer to the \s-1CGI\s0 docs for exact usage details. .PP Unlike calling \f(CW\*(C`header_props()\*(C'\fR, \f(CW\*(C`header_add()\*(C'\fR will preserve any existing headers. If a scalar value is passed to \f(CW\*(C`header_add()\*(C'\fR it will replace the existing value for that key. .PP If an array reference is passed as a value to \f(CW\*(C`header_add()\*(C'\fR, values in that array ref will be appended to any existing values values for that key. This is primarily useful for setting an additional cookie after one has already been set. .PP \fI\f(BIheader_props()\fI\fR .IX Subsection "header_props()" .PP .Vb 1 \& $c\->header_props(\-type=>\*(Aqimage/gif\*(Aq,\-expires=>\*(Aq+3d\*(Aq); .Ve .PP The \f(CW\*(C`header_props()\*(C'\fR method expects a hash of \s-1CGI\s0.pm\-compatible \&\s-1HTTP\s0 header properties. These properties will be passed directly to \s-1CGI\s0.pm's \f(CW\*(C`header()\*(C'\fR or \f(CW\*(C`redirect()\*(C'\fR methods. Refer to \s-1CGI\s0 for exact usage details. .PP Calling header_props any arguments will clobber any existing headers that have previously set. .PP \&\f(CW\*(C`header_props()\*(C'\fR return a hash of all the headers that have currently been set. It can be called with no arguments just to get the hash current headers back. .PP To add additional headers later without clobbering the old ones, see \f(CW\*(C`header_add()\*(C'\fR. .PP \&\fB\s-1IMPORTANT NOTE REGARDING HTTP HEADERS\s0\fR .PP It is through the \f(CW\*(C`header_props()\*(C'\fR and \f(CW\*(C`header_add()\*(C'\fR method that you may modify the outgoing \s-1HTTP\s0 headers. This is necessary when you want to set a cookie, set the mime type to something other than \*(L"text/html\*(R", or perform a redirect. Understanding this relationship is important if you wish to manipulate the \s-1HTTP\s0 header properly. .PP \fI\f(BIredirect()\fI\fR .IX Subsection "redirect()" .PP .Vb 1 \& return $c\->redirect(\*(Aqhttp://www.example.com/\*(Aq); .Ve .PP Redirect to another \s-1URL.\s0 .PP \fI\f(BIforward()\fI\fR .IX Subsection "forward()" .PP .Vb 1 \& return $c\->forward(\*(Aqrm_name\*(Aq); .Ve .PP Pass control to another run mode and return its output. This is equivalent to calling \f(CW$self\fR\->$other_runmode, except that the internal value of the current run mode is updated. This bookkeeping is important to \fBload_tmpl()\fR when called with no arguments and some other plugins. .PP \fI\f(BIdbh()\fI\fR .IX Subsection "dbh()" .PP .Vb 2 \& sub cgiapp_init { \& my $c = shift; \& \& # use the same args as DBI\->connect(); \& $c\->dbh_config($data_source, $username, $auth, \e%attr); \& \& } \& \& sub form_process { \& my $c = shift; \& \& my $dbh = $c\->dbh; \& } .Ve .PP Easy access to a \s-1DBI\s0 database handle. The database connection is not created until the first call to \f(CW\*(C`dbh()\*(C'\fR. See CGI::Application::Plugin::DBH for more features and details. .PP \fI\f(BIsession()\fI\fR .IX Subsection "session()" .PP .Vb 4 \& # in cgiapp_init() \& $c\->session_config( \& CGI_SESSION_OPTIONS => [ "driver:PostgreSQL;serializer:Storable", $self\->query, {Handle=>$dbh} ], \& ); \& \& # in a run mode \& my $ses = $c\->session\->param(\*(Aqfoo\*(Aq); .Ve .PP Easy access to a CGI::Session object, so you can store user data between requests. The session is not accessed or created until the first call to \fBsession()\fR in a given request. See CGI::Application::Plugin::Session for more features and details. .PP \fI\f(BIcfg()\fI\fR .IX Subsection "cfg()" .PP .Vb 1 \& $c\->cfg(\*(Aqroot_uri\*(Aq); .Ve .PP Easy access to parameters loaded from a config file, which can be stored in one of several formats, including \s-1YAML\s0 and Pure Perl. For more features and details see CGI::Application::Plugin::ConfigAuto. .PP \fI\f(BIlog()\fI\fR .IX Subsection "log()" .PP .Vb 2 \& $c\->log\->info(\*(AqInformation message\*(Aq); \& $c\->log\->debug(\*(AqDebug message\*(Aq); .Ve .PP Easy access to a Log::Dispatch logging object, allowing you to log to different locations with different locations of severity. By adjusting the logging level for your application, you make \*(L"debug\*(R" messages appear or disappear from your logs without making pervasive code changes. See CGI::Application::Plugin::LogDispatch for more features and details. .PP \fI\f(BIcheck_rm()\fI\fR .IX Subsection "check_rm()" .PP .Vb 2 \& my ($results, $err_page) = $c\->check_rm(\*(Aqform_display\*(Aq,\*(Aq_form_profile\*(Aq); \& return $err_page if $err_page; .Ve .PP Easy form validation with Data::FormValidator. If the validation fails, we'll re-display the form for the user with their data pre-filled and the errors highlighted. You'll have full control over the design of the errors with \s-1HTML\s0 and \s-1CSS\s0 in your templates, although we provide some intelligent defaults. See CGI::Application::Plugin::ValidateRM for features and details. .PP \fI\f(BIfill_form()\fI\fR .IX Subsection "fill_form()" .PP .Vb 2 \& # fill an HTML form with data in a hashref or from an object with with a param() method \& my $filled_html = $self\->fill_form($html, $data); \& \& # ...or default to getting data from $self\->query() \& my $filled_html = $self\->fill_form($html); .Ve .PP HTML::FillInForm is a useful when you want to fill in a web form with default values from a database table. Like many \s-1CPAN\s0 modules, you can use directly from CGI::Application without any special plugin. The value of this plugin is that it defaults to finding values through \f(CW$self\fR\->\fBquery()\fR. Besides that, it is just a bit of synatic sugar that was mostly created work-around weaknesses in the HTML::FillInForm 1.x interface, which were fixed with HTML::FillInForm 2.0 release. See CGI::Application::Plugin::FillInForm for details. .PP \fI\f(BIerror()\fI\fR .IX Subsection "error()" .PP .Vb 1 \& $c\->error( title => \*(Aq..\*(Aq, msg => \*(Aq..\*(Aq ); .Ve .PP Provide quick error messages back to the user for exceptional cases. You can provide your own custom designed template or use the default one built-in. See CGI::Application::Plugin::ErrorPage. .PP \fI\f(BIstream_file()\fI\fR .IX Subsection "stream_file()" .PP .Vb 1 \& $c\->stream_file($file); .Ve .PP If your run mode is outputting an image or a spreadsheet instead of an \s-1HTML\s0 page, you may want to stream the output. This method takes care of the boring details of buffering, headers and \s-1MIME\s0 types. See CGI::Application::Plugin::Stream for details. .PP \fI\f(BIprerun_mode()\fI\fR .IX Subsection "prerun_mode()" .PP .Vb 1 \& $c\->prerun_mode(\*(Aqnew_run_mode\*(Aq); .Ve .PP The \fBprerun_mode()\fR method is an accessor/mutator which can be used within your \fBcgiapp_prerun()\fR method to change the run mode which is about to be executed. For example, consider: .PP .Vb 5 \& # In WebApp.pm: \& package WebApp; \& use base \*(AqTitanium\*(Aq; \& sub cgiapp_prerun { \& my $c = shift; \& \& # Get the web user name, if any \& my $q = $c\->query(); \& my $user = $q\->remote_user(); \& \& # Redirect to login, if necessary \& unless ($user) { \& $c\->prerun_mode(\*(Aqlogin\*(Aq); \& } \& } .Ve .PP In this example, the web user will be forced into the \*(L"login\*(R" run mode unless they have already logged in. The \fBprerun_mode()\fR method permits a scalar text string to be set which overrides whatever the run mode would otherwise be. .PP The \fBprerun_mode()\fR method should be used in cases where you want to use Titanium's normal run mode switching facility, but you want to make selective changes to the mode under specific conditions. .PP \&\fBNote:\fR The \fBprerun_mode()\fR method may \s-1ONLY\s0 be called in the context of a \fBcgiapp_prerun()\fR method. Your application will \fBdie()\fR if you call \&\fBprerun_mode()\fR elsewhere, such as in \fBsetup()\fR or a run mode method. .SS "Dispatching Clean URIs to run modes" .IX Subsection "Dispatching Clean URIs to run modes" Modern web frameworks dispense with cruft in URIs, providing in clean URIs instead. Instead of: .PP .Vb 1 \& /cgi\-bin/item.cgi?rm=view&id=15 .Ve .PP A clean \s-1URI\s0 to describe the same resource might be: .PP .Vb 1 \& /item/15/view .Ve .PP The process of mapping these URIs to run modes is called dispatching and is handled by CGI::Application::Dispatch. Dispatching is not required and is a layer you can fairly easily add to an application later. .SS "Offline website development" .IX Subsection "Offline website development" You can work on your Titanium project on your desktop or laptop without installing a full-featured web-server like Apache. Instead, install CGI::Application::Server from \s-1CPAN.\s0 After a few minutes of setup, you'll have your own private application server up and running. .SS "Automated Testing" .IX Subsection "Automated Testing" There a couple of testing modules specifically made for Titanium. .PP Test::WWW::Mechanize::CGIApp allows functional testing of a CGI::App\-based project without starting a web server. Test::WWW::Mechanize could be used to test the app through a real web server. .PP Test::WWW::Selenium is similar, but uses Selenium for the testing, meaning that a local web-browser would be used, allowing testing of websites that contain JavaScript. .PP Direct testing is also easy. Titanium will normally print the output of its run modes directly to \s-1STDOUT.\s0 This can be suppressed with an environment variable, \&\s-1CGI_APP_RETURN_ONLY.\s0 For example: .PP .Vb 3 \& $ENV{CGI_APP_RETURN_ONLY} = 1; \& $output = $c\->run; \& like($output, qr/good/, "output is good"); .Ve .PP Examples of this style can be seen in our own test suite. .SH "PLUGINS" .IX Header "PLUGINS" Titanium has a plug-in architecture that is easy to use and easy to develop new plug-ins for. Plugins made for CGI::Application are directly compatible. The CGI::Application should be referenced for those who wish to write plugins. .PP Select plugins are listed below. For a current complete list, please consult \&\s-1CPAN:\s0 .PP http://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin .IP "\(bu" 4 CGI::Application::Plugin::Apache \- Use Apache::* modules without interference .IP "\(bu" 4 CGI::Application::Plugin::AutoRunmode \- Automatically register runmodes .IP "\(bu" 4 CGI::Application::Plugin::CompressGzip \- Add Gzip compression .IP "\(bu" 4 CGI::Application::Plugin::TT \- Use Template::Toolkit as an alternative to HTML::Template. .PP Consult each plug-in for the exact usage syntax. .SH "COMMUNITY" .IX Header "COMMUNITY" Therese are primary resources available for those who wish to learn more about Titanium and discuss it with others. .PP \&\fBWiki\fR .PP This is a community built and maintained resource that anyone is welcome to contribute to. It contains a number of articles of its own and links to many other Titanium related pages. It is currently branded as CGI::Application, but the code is the same. .PP .PP \&\fBSupport Mailing List\fR .PP If you have any questions, comments, bug reports or feature suggestions, post them to the support mailing list! To join the mailing list, simply send a blank message to \*(L"cgiapp\-subscribe@lists.erlbaum.net\*(R". .PP \&\fB\s-1IRC\s0\fR .PP You can also drop by \f(CW\*(C`#cgiapp\*(C'\fR on \f(CW\*(C`irc.perl.org\*(C'\fR with a good chance of finding some people involved with the project there. .PP \&\fBSource Code\fR .PP This project is managed using the darcs source control system ( http://www.darcs.net/ ). The darcs archive is here: http://mark.stosberg.com/darcs_hive/titanium .SH "TODO" .IX Header "TODO" * I would like Titanium to be easier to install and get started with. Rather than depending on the large \s-1CPAN\s0 dependency chain being installed, I would like an option for users to download the full stack of dependencies, so that you can just unpack a single file and go. .PP * I'd like a plugin to cope with the URI-encoding that Dreamweaver does to templates that may just mean packing and releasing the following code as a plug-in: .PP .Vb 2 \& CGI::Application\->add_callback(\*(Aqload_tmpl\*(Aq,sub { \& my ($c, $ht_params, $tmpl_params, $tmpl_file) = @_; \& \& require HTML::Template::Filter::URIdecode; \& import HTML::Template::Filter::URIdecode \*(Aqht_uri_decode\*(Aq; \& \& # If you already have a filter defined, don\*(Aqt do anything. \& # If you want to add more of your own filters later, be mindful \& # about whether you add to this arrayref, or replace it. \& unless ($ht_params\->{filter}) { \& $ht_params\->{filter} = [\e&ht_uri_decode] \& } \& }); .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" .IP "\(bu" 4 CGI::Application .SH "MORE READING" .IX Header "MORE READING" If you're interested in finding out more about Titanium, the following articles are available on Perl.com, providing context about the underlying CGI::Application framework .PP .Vb 2 \& Using CGI::Application \& http://www.perl.com/pub/a/2001/06/05/cgi.html \& \& Rapid Website Development with CGI::Application \& http://www.perl.com/pub/a/2006/10/19/cgi_application.html .Ve .PP Thanks to O'Reilly for publishing these articles, and for the incredible value they provide to the Perl community! .SH "AUTHORS" .IX Header "AUTHORS" Many. .PP Mark Stosberg, \f(CW\*(C`mark@summersault.com\*(C'\fR published the original Titanium module, while many another contributed to CGI::Application and the related plugins. .SH "LICENSE" .IX Header "LICENSE" Copyright (C) 2008, Mark Stosberg. .PP This module is free software; you can redistribute it and/or modify it under the terms of either: .PP a) the \s-1GNU\s0 General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, .PP or .PP b) the \*(L"Artistic License\*(R". .PP This program is distributed in the hope that it will be useful, but \s-1WITHOUT ANY WARRANTY\s0; without even the implied warranty of \&\s-1MERCHANTABILITY\s0 or \s-1FITNESS FOR A PARTICULAR PURPOSE.\s0 See either the \s-1GNU\s0 General Public License or the Artistic License for more details.