Titanium(3pm)
โจ NAME โจ
okay so bestie, this is Titanium(3pm) and it's literally a strong, lightweight web application framework. The module itself is Titanium โ A strong, lightweight web application framework. No cap, it's giving main character energy for Perl web apps. ๐
๐ฆ
๐ SYNOPSIS ๐
๐ป Coding ๐ป
okay so first, the coding vibe. In WebApp.pm you set it up like this, and then webapp.cgi runs the whole thing:
# In "WebApp.pm"...
package WebApp;
use base 'Titanium';
sub setup {
my $c = shift;
$c->start_mode('form_display');
$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('form_display','_form_profile');
return $err_page if $err_page;
return $c->forward('form_success');
}
# Return a Data::FormValidator profile
sub _form_profile {
my $c = shift;
return {
required => 'email',
};
}
sub form_success { ... }
1;
### In "webapp.cgi"...
use WebApp;
my $c = WebApp->new();
$c->run();
Inside the run modes, the following methods are available:
$c->query; # A query object. CGI.pm by default.
$c->redirect('http://othersite.com'); # Basic redirection
$c->dbh; # DBI database handle
$c->session(); # A CGI::Session object
$c->check_rm; # Form validation with Data::FormValidator
$c->cfg('root_uri'); # Config file access (YAML, Perl or INI formats)
$c->fill_form; # Form filling with HTML::FillInForm
$c->error( title => '..', msg => '..' ); # Easy error page generation
$c->stream_file($file); # file streaming
$c->log; # A Log::Dispatch object
๐งช Development and Testing ๐งช
okay so for dev and testing, you can easily setup the project skeleton using the bundled cgiapp-starter script. 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. 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. It's lowkey a whole vibe. ๐งชโจ
๐ฃ๏ธ Dispatching with Clean URIs ๐ฃ๏ธ
Modern web frameworks dispense with cruft in URIs. Instead of:
/cgi-bin/item.cgi?rm=view&id=15
A clean URI to describe the same resource might be:
/item/15/view
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:
/app/module_name/run_mode
There's plenty of flexibility to design your own URIs if you'd like. Slay. ๐ฃ๏ธ
๐ Elements of Titanium ๐
- Titanium is solid and mature. ngl, while it has a new name, the reality is that Titanium is simply a more user-friendly packaging of the mature
CGI::Applicationframework 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 "Titanium alloys" in the "Titanium::Alloy::" name space may also come to exist, following the same philosophy, but choosing to bundle a different combination of plugins. Periodt. ๐ - Titanium is lightweight. fr 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
DBIor make a database connection until you actually use the database connection. Titanium runs well in a plain CGI 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 forCGI::Application, so you can add additional features as your needs evolve. Iconic. โจ
๐ธ DESCRIPTION ๐ธ
okay so the whole point is that your Application Module will be implemented as a sub-class of Titanium. This is done simply as follows:
package My::App;
use base 'Titanium';
โ๏ธ Notation and Conventions โ๏ธ
For the purpose of this document, we will refer to the following conventions:
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".
๐น๏ธ 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. These are your script-side besties. ๐ซถ
๐ new()
The new() method is the constructor for a Titanium. It returns a blessed reference to your Application Module class. Optionally, new() may take a set of parameters as key => value pairs:
my $c = WebApp->new(
TMPL_PATH => 'App/',
PARAMS => {
'custom_thing_1' => 'some val',
'another_custom_thing' => [qw/123 456/]
}
);
This method may take some specific parameters:
TMPL_PATHโ This optional parameter defines a path to a directory of templates. This is used by theload_tmpl()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.QUERYโ This optional parameter allows you to specify an already-created CGI query object. Under normal use, Titanium will instantiate its ownCGI.pmquery object. Under certain conditions, it might be useful to be able to use one which has already been created.PARAMSโ 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,Mailform.pm. The application takes the contents of a HTML form and emails it to a specified recipient. You could have multiple instance scripts throughout your site which all use thisMailform.pmmodule, but which set different recipients or different forms.
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.
my $app = WebApp->new(PARAMS => { cfg_file => 'config.pl' });
# Later in your app:
my %cfg = $c->cfg()
# or ... $c->cfg('HTML_ROOT_DIR');
See the list of of plugins below for more config file integration solutions.
๐ run()
The run() method is called upon your Application Module object, from your Instance Script. When called, it executes the functionality in your Application Module.
my $c = WebApp->new;
$c->run;
This method determines the application state by looking at the dispatch table, as described in CGI::Application::Dispatch.
Once the mode has been determined, run() looks at the hash stored in run_modes() and finds the subroutine which is tied to a specific hash key. If found, the function is called and the data returned is print()'ed to STDOUT and to the browser. If the specified mode is not found in the run_modes() table, run() will croak(). This 'death' can possibly be captured and handled using error_mode(), described below. So maybe don't ghost your run modes, bestie. ๐
๐ ๏ธ 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:
setup()
This method is called by the inherited new() constructor method. The setup() method should be used to define the following property/methods:
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.
Your setup() 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 $c->param() method.
Your setup() method might be implemented something like this:
sub setup {
my $c = shift;
$c->start_mode('putform');
$c->run_modes([qw/
form
form_process
/]);
}
๐งฐ 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.
load_tmpl()
my $tmpl_obj = $c->load_tmpl;
my $tmpl_obj = $c->load_tmpl('some.html');
my $tmpl_obj = $c->load_tmpl( \$template_content );
my $tmpl_obj = $c->load_tmpl( FILEHANDLE );
This method takes the name of a template file, a reference to template data 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.
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.
( For integration with other template systems and automated template names, see "Alternatives to load_tmpl() below. )
When you hand it a filename, HTML::Template->new_file() is the constructor that gets used to make the object โจ. Pass in a reference to the template content instead, and it's HTML::Template->new_scalar_ref() doing the work. Hand it a filehandle, and boom โ HTML::Template->new_filehandle() steps up. Bestie, it just knows what you meant ๐
For the specifics on how you actually use HTML::Template, go read HTML::Template. That's the source of truth, fr.
If tmpl_path() has been specified, load_tmpl() will set the HTML::Template "path" option to the path(s) you gave it. This lowkey helps you encapsulate your template usage even more ๐ซถ.
The load_tmpl() method passes any extra parameters you send it straight on through to HTML::Template->new_file() (or new_scalar_ref() or new_filehandle()). So you can customize that HTML::Template object however you want:
my $tmpl_obj = $c->load_tmpl('some_other.html',
die_on_bad_params => 0,
cache => 1
);
Heads up though ๐ โ if you wanna pass extra args but still use the default template name, you still have to provide a name of "undef":
my $tmpl_obj = $c->load_tmpl(undef',
die_on_bad_params => 0,
cache => 1
);
โจ Alternatives to load_tmpl() โจ
If your app needs something more specialized than all that, no worries โ you can always replace it by overriding load_tmpl() and implementing your very own load_tmpl() in your Titanium sub-class application module. Main character energy, go off ๐
.
First though, you might wanna check out the template-related plugins.
CGI::Application::Plugin::TT focuses just on Template Toolkit integration, and it comes with pre-and-post features, singleton support and more. Slay.
๐ธ param() ๐ธ
$c->param('pname', $somevalue);
The param() method gives you a whole facility through which you can set application instance properties that are accessible throughout your entire application ๐ซถ.
You can use param() in two basic ways. First, use it to get or set the value of a parameter:
$c->param('scalar_param', '123');
my $scalar_param_values = $c->param('some_param');
Second, when it's called in the context of an array, with no parameter name specified, param() returns an array containing all the parameters that currently exist:
my @all_params = $c->param();
The param() method also lets you set a whole bunch of parameters at once by passing in a hash (or a hashref):
$c->param(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3',
);
Okay so here's why param() is iconic ๐: it enables a super valuable system for customizing your applications on a per-instance basis. One Application Module might get instantiated by different Instance Scripts. Each Instance Script might set different values for a set of parameters. And that means similar applications can share a common code-base but behave differently โ which is the dream, honestly. Picture a mail form application with a single Application Module but multiple Instance Scripts. Each Instance Script might specify a different recipient ๐ฌ. Another example: a web bulletin board system, with multiple boards, each with its own topic and set of administrators.
The new() method gives you a shortcut for specifying a number of run-time parameters all at once. Internally, Titanium calls the param() method to set these properties. So yeah โ param() is a powerful tool for greatly increasing your application's re-usability. Periodt.
๐ฆ query() ๐ฆ
my $q = $c->query();
my $remote_user = $q->remote_user();
This method retrieves the CGI.pm query object that was created by instantiating your Application Module. For the details on how to use that query object, refer to CGI. Titanium is built on the CGI module, so ngl you're gonna wanna get very familiar with CGI.pm โ you'll be reaching for the query object whenever you want to interact with form data ๐.
When the new() method is called, a CGI query object gets automatically created. But if for some reason you wanna use your own CGI query object, the new() method supports passing in your existing query object on construction using the QUERY attribute. Your rules, bestie ๐
.
๐ run_modes() ๐
# 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(
'mode1' => 'some_sub_by_name',
'mode2' => \&some_other_sub_by_ref
);
This accessor/mutator specifies a lookup table for the application states, using the syntax examples above. It returns the dispatch table as a hash.
The run_modes() method may be called more than once. Additional values passed into run_modes() get added to the run modes table. And if an existing run mode gets re-defined, the new value overrides the existing value. This behavior might be useful for applications created via inheritance from another application, or for some advanced application that modifies its own capabilities based on user input. Clever girl โจ.
The run() 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 "run mode methods".
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 you want called when the application enters the specified run mode, or the name of the run mode method to be called:
'mode_name_by_ref' => \&mode_function
'mode_name_by_name' => 'mode_function'
The run mode method you specify is expected to return a block of text (like, HTML) which will eventually get sent back to the web browser ๐. The run mode method may return its block of text as a scalar or a scalar-ref.
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 that's exactly the same as an existing application except for one run mode, you could simply inherit from that other application and override the run mode method that's different. But if you specified your run mode method by reference, your child class would still use the function from the parent class. ๐
An advantage of specifying your run mode methods by reference instead of by name is performance. Dereferencing a subref is faster than eval()-ing a code block. So 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. ๐
Specifying the run modes by array reference:
$c->run_modes([ 'mode1', 'mode2', 'mode3' ]);
Is is the same as using a hash, with keys equal to values:
$c->run_modes(
'mode1' => 'mode1',
'mode2' => 'mode2',
'mode3' => 'mode3'
);
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 the verbosity of your code. Less typing, same slay ๐ซถ.
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 "default-deny" stance on all method invocation, thereby allowing secure applications to be built upon it. No cap, that's the whole point. ๐
๐ IMPORTANT NOTE ABOUT RUN MODE METHODS ๐
Your application should *NEVER* print() to STDOUT. Using print() to send output to STDOUT (including HTTP headers) is exclusively the domain of the inherited run() method. Breaking this rule is a common source of errors. So if your program is erroneously sending content before your HTTP header, you are probably breaking this rule. Don't do it bestie, I'm begging ๐
๐ THE RUN MODE OF LAST RESORT: "AUTOLOAD" ๐
If Titanium is asked to go to a run mode which doesn't exist, by default it'll return an error page to the user, implemented like this:
return $c->error(
title => 'The requested page was not found.',
msg => "(The page tried was: ".$c->get_current_runmode.")"
);
See CGI::Application::Plugin::ErrorPage for more details on the built-in error page system. If that's not the behavior you want for handling unknown run mode requests, implement your own run mode with the reserved name "AUTOLOAD":
$c->run_modes(
"AUTOLOAD" => \&catch_my_exception
);
Before Titanium invokes its own error page handling, it will check for the existence of a run mode called "AUTOLOAD". If specified, this run mode gets invoked just like a regular run mode, with one exception: it receives, as an argument, the name of the run mode which invoked it:
sub catch_my_exception {
my $c = shift;
my $intended_runmode = shift;
my $output = "Looking for '$intended_runmode', but found 'AUTOLOAD' instead";
return $output;
}
This functionality could be [used] for more sophisticated application behaviors. ๐ง
๐ start_mode() ๐
$c->start_mode('mode1');
The start_mode contains the name of the mode as specified in the run_modes() table. Default mode is "start". The mode key specified here gets used whenever the value of the CGI form parameter specified by mode_param() is not defined. Generally, this is the first time your application is executed โจ.
โญ tmpl_path() โญ
$c->tmpl_path('/path/to/some/templates/');
This access/mutator method sets the file path to the directory (or directories) where the templates are stored. It's used by load_tmpl() to find the template files, using HTML::Template's "path" option. To set the path you can either pass in a text scalar or an array reference of multiple paths. Your call, bestie ๐.
๐ซถ More Methods to override ๐ซถ
Several more non-essential methods are useful to declare in your application class, or in a project "super class" that inherits from your Titanium only to serve in turn as a base class for project modules. These additional methods are as follows:
๐ธ teardown() ๐ธ
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 teardown() function is to disconnect a database connection which was established in the setup() function, or flush open session data. You could also use the teardown() method to store state information about the application to the server. Tidy up, queen ๐งนโจ
๐ cgiapp_init() ๐
okay so bestie, if it's implemented, this method gets called automatically right the heck before the setup() method runs. And cgiapp_init() takes, as its parameters, all the arguments that were passed to the new() method. cute, right? ๐
One lowkey iconic reason you'd want this hook: building your own custom "application super-class" that all your web apps inherit from, instead of inheriting straight from Titanium. like, a shared mom friend for all your apps ๐
peep this:
# In MySuperclass.pm:
package MySuperclass;
use base 'Titanium';
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 'MySuperclass';
sub setup { ... }
sub teardown { ... }
# The rest of your Titanium-based follows...
so by using Titanium and cgiapp_init() like that, a whole suite of apps can be designed to share certain characteristics, which means cleaner code. slay. โจ
cgiapp_prerun()
If it's implemented, this method gets called automatically right before the selected run mode method runs. It's an optional pre-runmode hook โ a little moment to add functionality right before the run mode method is called. The value of the run mode gets passed into cgiapp_prerun(). ๐ฆ
A custom "application super-class" (that all your web apps inherit from, instead of Titanium directly) could totally use this. consider:
# In MySuperclass.pm:
package MySuperclass;
use base 'Titanium';
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 'MySuperclass';
sub setup { ... }
sub teardown { ... }
# The rest of your Titanium-based follows...
Also!! inside your cgiapp_prerun() method you can literally change the run mode of your application. how? via the prerun_mode() method, which is discussed elsewhere. go find it bestie ๐ฅ
cgiapp_postrun()
If you implement this hook, it gets called after the run mode method has returned its output, but before HTTP headers are generated. so you get a lil window to modify the body and the headers before they head back to the web browser. main character moment honestly ๐
The classic use for this hook is pipelining the output of a CGI-Application through a series of "filter" processors. for example:
- 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.
The cgiapp_postrun() hook receives a reference to the output from your run mode method, plus the CGI-App object. a typical cgiapp_postrun() method might look like this:
sub cgiapp_postrun {
my $c = shift;
my $output_ref = shift;
# Enclose output HTML table
my $new_output = "<table border=1>";
$new_output .= "<tr><td> Hello, World! </td></tr>";
$new_output .= "<tr><td>". $$output_ref ."</td></tr>";
$new_output .= "</table>";
# Replace old output with new output
$$output_ref = $new_output;
}
obviously, since you've got access to the CGI-App object, you have full access to all the methods normally available in a run mode. like, you could use load_tmpl() to swap out the static HTML in this example for HTML::Template. you could change the HTTP headers (via header_add() ). you could also use the object's properties to apply changes only under certain circumstances โ for example only in certain run modes, and when a param() is a particular value. iykyk ๐
cgiapp_get_query()
my $q = $c->cgiapp_get_query;
Override this method to retrieve the query object if you want to use a different query interface instead of CGI.pm. ๐ง
CGI.pm is only loaded to provided query object is only loaded if it used on a given request.
If you can use an alternative to CGI.pm, it needs to have some compatibility with the CGI.pm API. For normal use, just having a compatible param method should be sufficient.
If use the path_info option to the mode_param() method, then we will call the path_info() method on the query object.
If you use the Dump method in Titanium, we will call the Dump and escapeHTML methods on the query object.
๐ More Application Methods ๐
You can skip this section if you are just getting started. (fr, no pressure bestie ๐ซถ)
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. so organized of them ๐
error_mode()
$c->error_mode('my_error_rm');
If the runmode dies for whatever reason, run() will see if you have set a value for error_mode(). If you have, run() will call that method as a run mode, passing $@ as the only parameter. ๐ญ
No error_mode is defined by default. The death of your error_mode() run mode is not trapped, so you can also use it to die in your own special way. dramatic. we love that for you ๐
For a complete integrated logging solution, check out CGI::Application::Plugin::LogDispatch.
header_add()
# add or replace the 'type' header
$c->header_add( -type => 'image/png' );
- or -
# add an additional cookie
$c->header_add(-cookie=>[$extra_cookie]);
The header_add() method is used to add one or more headers to the outgoing response headers. The parameters will eventually be passed on to the CGI.pm header() method, so refer to the CGI docs for exact usage details. โจ
Unlike calling header_props(), header_add() will preserve any existing headers. If a scalar value is passed to header_add() it will replace the existing value for that key.
If an array reference is passed as a value to header_add(), 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. ๐
header_props()
$c->header_props(-type=>'image/gif',-expires=>'+3d');
The header_props() method expects a hash of CGI.pm-compatible HTTP header properties. These properties will be passed directly to CGI.pm's header() or redirect() methods. Refer to CGI for exact usage details.
Calling header_props any arguments will clobber any existing headers that have previously set. ๐ฑ
header_props() 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.
To add additional headers later without clobbering the old ones, see header_add().
๐ฅ IMPORTANT NOTE REGARDING HTTP HEADERS ๐ฅ
It is through the header_props() and header_add() method that you may modify the outgoing HTTP headers. This is necessary when you want to set a cookie, set the mime type to something other than text/html, or perform a redirect. Understanding this relationship is important if you wish to manipulate the HTTP header properly. no cap, this one matters ๐
redirect()
return $c->redirect('http://www.example.com/');
Redirect to another URL. bye bestie, we're going elsewhere ๐
forward()
return $c->forward('rm_name');
Pass control to another run mode and return its output. This is equivalent to calling $self->$other_runmode, except that the internal value of the current run mode is updated. This bookkeeping is important to load_tmpl() when called with no arguments and some other plugins. ๐ฅ
dbh()
sub cgiapp_init {
my $c = shift;
# use the same args as DBI->connect();
$c->dbh_config($data_source, $username, $auth, \%attr);
}
sub form_process {
my $c = shift;
my $dbh = $c->dbh;
}
Easy access to a DBI database handle. The database connection is not created until the first call to dbh(). See CGI::Application::Plugin::DBH for more features and details. lazy loading queen ๐
session()
# 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('foo');
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 session() in a given request. See CGI::Application::Plugin::Session for more features and details. ๐ธ
cfg()
$c->cfg('root_uri');
Easy access to parameters loaded from a config file, which can be stored in one of several formats, including YAML and Pure Perl. For more features and details see CGI::Application::Plugin::ConfigAuto. โจ
log()
$c->log->info('Information message');
$c->log->debug('Debug message');
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 debug messages appear or disappear from your logs without making pervasive code changes. See CGI::Application::Plugin::LogDispatch for more features and details. ๐ฆ
check_rm()
my ($results, $err_page) = $c->check_rm('form_display','_form_profile');
return $err_page if $err_page;
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 HTML and CSS in your templates, although we provide some intelligent defaults. See CGI::Application::Plugin::ValidateRM for features and details. ๐
fill_form()
# 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);
okay so bestie, HTML::FillInForm is literally the moment when you wanna fill in a web form with default values from a database table. Like so many CPAN modules, you can just use it directly from CGI::Application without any special plugin. The whole vibe of this plugin is that it defaults to finding values through $self->query(). Other than that? It's just a lil bit of syntactic sugar that was mostly created to work around the weaknesses in the HTML::FillInForm 1.x interface, which got fixed with the HTML::FillInForm 2.0 release. See CGI::Application::Plugin::FillInForm for the deets. ๐
โจ error() โจ
$c->error( title => '..', msg => '..' );
Need to send a quick error message back to the user for those exceptional cases? This is your girl. You can provide your own custom designed template or just use the default one that's built-in. See CGI::Application::Plugin::ErrorPage for all the tea. ๐ญ
๐ stream_file() ๐
$c->stream_file($file);
If your run mode is outputting an image or a spreadsheet instead of an HTML page, you might wanna stream the output. This method handles all the boring details of buffering, headers and MIME types for you. See CGI::Application::Plugin::Stream for the details. ๐ผ๏ธ
๐ฎ prerun_mode() ๐ฎ
$c->prerun_mode('new_run_mode');
The prerun_mode() method is an accessor/mutator that you can use inside your cgiapp_prerun() method to change the run mode that's about to be executed. For example, check this out:
# In WebApp.pm:
package WebApp;
use base 'Titanium';
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('login');
}
}
In this example, the web user gets forced into the "login" run mode unless they've already logged in. The prerun_mode() method lets you set a scalar text string that overrides whatever the run mode would otherwise be. โจ
You should use prerun_mode() when you wanna use Titanium's normal run mode switching facility, but you need to make selective changes to the mode under specific conditions. ๐
Note: Theprerun_mode()method may ONLY be called in the context of acgiapp_prerun()method. Your application willdie()if you callprerun_mode()anywhere else, like insetup()or a run mode method. So don't do that bestie, fr fr. ๐
๐ Dispatching Clean URIs to run modes ๐
Modern web frameworks literally dispense with cruft in URIs, giving you clean URIs instead. So instead of:
/cgi-bin/item.cgi?rm=view&id=15
a clean URI to describe the same resource might be:
/item/15/view
The process of mapping these URIs to run modes is called dispatching, and it's handled by CGI::Application::Dispatch. Dispatching is not required, and it's a layer you can pretty easily add to an application later. No pressure. ๐ฆ
๐ป 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, just install CGI::Application::Server from CPAN. After a few minutes of setup, you'll have your own private application server up and running. Iconic. ๐
๐งช Automated Testing ๐งช
There are a couple of testing modules specifically made for Titanium. โจ
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. ๐
Test::WWW::Selenium is similar, but uses Selenium for the testing, meaning a local web-browser would be used, allowing testing of websites that contain JavaScript. ๐
Direct testing is also easy. Titanium will normally print the output of its run modes directly to STDOUT. This can be suppressed with an environment variable, CGI_APP_RETURN_ONLY. For example:
$ENV{CGI_APP_RETURN_ONLY} = 1;
$output = $c->run;
like($output, qr/good/, "output is good");
Examples of this style can be seen in our own test suite. ๐
๐ PLUGINS ๐
Titanium has a plug-in architecture that's 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 wanna write plugins. ๐ฉโ๐ป
Here are some select plugins. For a current complete list, please consult CPAN:
http://search.cpan.org/search?m=dist&q=CGI%2DApplication%2DPlugin
CGI::Application::Plugin::Apache- UseApache::*modules without interferenceCGI::Application::Plugin::AutoRunmode- Automatically register runmodesCGI::Application::Plugin::CompressGzip- Add Gzip compressionCGI::Application::Plugin::TT- UseTemplate::Toolkitas an alternative toHTML::Template.
Consult each plug-in for the exact usage syntax. ๐
๐ COMMUNITY ๐
These are primary resources available for those who wanna learn more about Titanium and discuss it with others. ๐ซถ
๐ Wiki ๐
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's currently branded as CGI::Application, but the code is the same. ๐
๐ Support Mailing List ๐
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 "cgiapp-subscribe@lists.erlbaum.net". ๐ง
๐ฌ IRC ๐ฌ
You can also drop by "#cgiapp" on "irc.perl.org" with a good chance of finding some people involved with the project there. ๐
๐ฆ Source Code ๐ฆ
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 ๐๏ธ
๐ TODO ๐
* I would like Titanium to be easier to install and get started with. Rather than depending on the large CPAN 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. ๐
* 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:
CGI::Application->add_callback('load_tmpl',sub {
my ($c, $ht_params, $tmpl_params, $tmpl_file) = @_;
require HTML::Template::Filter::URIdecode;
import HTML::Template::Filter::URIdecode 'ht_uri_decode';
# If you already have a filter defined, don't 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} = [\&ht_uri_decode]
}
});
๐ SEE ALSO ๐
CGI::Application
๐ 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. ๐
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
Thanks to O'Reilly for publishing these articles, and for the incredible value they provide to the Perl community! ๐
๐ AUTHORS ๐
Many. โจ
Mark Stosberg, "mark@summersault.com" published the original Titanium module, while many another contributed to CGI::Application and the related plugins. ๐
๐ LICENSE ๐
Copyright (C) 2008, Mark Stosberg.
This module is free software; you can redistribute it and/or modify it under the terms of either:
a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version,
or
b) the "Artistic License".
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the GNU General Public License or the Artistic License for more details. โ ๏ธ
That's all bestie! This page is from Titanium(3pm), version perl v5.30.3, dated 2020-08-22. Stay slaying! ๐ โจ
๐ฆ where this page comes from
- debian bookworm: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu jammy: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libtitanium-perl 1.04-5 ยท Artistic-1.0-Perl OR GPL-1.0-or-later
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms