On Sat, 18 Jan 2003, Simon Wistow wrote:

> 
> It's been a while since I've done a full blown web app, especially with
> a templating system, and I'd appreciate some advice.
> 
> Single CGI with a load of if/else statments based on mode or something
> ...
> 
> my $q    = new CGI();
> my $mode = $q->param('mode');
> 
> my $template = Template->new($config);
> 
> my $template = 'default' 
> my $vars     = {};
> 
> if ($mode eq 'foo') {
>       
>       $template      = 'foo';
>       $vars->{quux}  = 'something';
> 
> } elsif ($mode eq 'bar') {
> 
>       $template      = 'bar';
>       $vars->{quux}  = 'something else';
>       $vars->{quirk} = 5;
> }
> 
> $template->process($template, $vars)
>              || die $template->error();
> 
> 
> Or individual CGIs for every single template?
> 
> There are quite a few templates, about 20 or 30 if that makes a
> difference.

I've been converted to using dispatch tables for this sort of thing. See 
Ziggy's paper at:

http://www.usenix.org/publications/login/2002-06/pdfs/turoff.pdf


Your code might look something like (untested):

my $q = new CGI();
my $mode = $q->param('mode') || 'default';

my %app = ( q        => $q,
            mode     => $mode,
            template => 'default',
            vars     => {},
          );

my %dispatch = ( default => \&do_default,
                 foo     => \&do_foo,
                 bar     => \&do_bar,
               );

$mode = 'default' unless exists $dispatch{ $mode };

$dispatch{ $mode }->( \%app );

my $template = Template->new($config);

$template->process($app{ template }, $app{ vars })
             || die $template->error();

sub do_foo {
  my $app = shift;
  $app->{ template } = 'foo';
  $app->{ vars }->{ quux } = 'something';
}

# repeat for other subs.

I've found that it makes extending the functionality trivial and results 
in less nesting and easier to understand and maintain code. It's also 
really useful when you want to add a second selection criteria, such as 
whether or not someone is authorised. It's all in Ziggy's paper.

Simon.

-- 
"They tend to come out a colour called 'Pants left in wash' "
 



Reply via email to