Background
Below is a typical piece of Perl code (sample.pl for the sake of discussion) that grabs submitted form data using CGI, passes the form data to DBI which will then retrieve the required rows from MySQL and then hands the results over to Template Toolkit to render into a HTML document for display.
Code listing for sample.pl :
#!/usr/bin/perl
use strict;
use CGI;
use DBI:
use Template;
#Grab submitted form data
my $cgi = CGI->new();
my $idFromSomewhere= $cgi->param('id');
my $driver = "mysql";
my $server = "localhost:3306";
my $database = "test";
my $url = "DBI:$driver:$database:$server";
my $user = "apache";
my $password = "";
#Connect to database
my $db_handle = DBI->connect( $url, $user, $password )
or die $DBI::errstr;
#SQL query to execute
my $sql = "SELECT * FROM tests WHERE id=?";
#Prepare SQL query
my $statement = $db_handle->prepare($sql)
or die "Couldn't prepare query '$sql': $DBI::errstr\n";
#Execute SQL Query
$statement->execute($idFromSomewhere)
or die "Couldn't execute query '$sql': $DBI::errstr\n";
#Get query results as hash
my $results = $statement->fetchall_hashref('id');
$db_handle->disconnect();
my $tt = Template->new();
#HTML output template
my $input = 'template.html';
my $vars = {
tests => $results,
};
#Process template and output as HTML
$tt->process($input, $vars)
or die $tt->error();
For better performance and scalability, web hosts providing shared servers, such as Dreamhost, strongly recommend that all production Perl script support FastCGI. The FastCGI documentation is pretty clear on how to modify existing Perl code to support FastCGI. The simple code below is often given as an example:
use FCGI;
while (FCGI::accept >= 0)
{
#Run existing code.
}
What's not so clear is where and what to put in the while loop.
Sub Questions
A. Should the code in sample.pl be simply wrapped around the existing code like so:
while (FCGI::accept >= 0)
{
#Grab submitted form data
my $cgi = CGI->new();
...
...
#Process template and output as HTML
$tt->process($input, $vars)
or die $tt->error();
}
B. Or is there more to it? For instance, should the code that handles the cgi, database and template be refactored into their own subs?
C. Should DBI->connect() and $db_handle->disconnect() be called inside or outside the FCGI while loop and what are the performance implications?
D. Should $tt->process() be called inside or outside the FCGI while loop?