[Catalyst] [OT] Best way to have the controller do something just

Jonathan Rockway jon at jrock.us
Mon Sep 4 01:15:34 CEST 2006


> undef *{ __PACKAGE__ . "::begin" };

This is admittedly the first thing that came to mind, but the man page
recommends that you write undef $package::{symbol} instead.  Here's an
example:

use strict;
my $foo = 'bar';
sub foo { print "foo\n" }
foo;
undef $main::{foo};
eval{ foo }; warn $@;
print $foo. "\n"

It prints what you would expect:

foo
Undefined subroutine &main::foo called at - line 6.
bar

However, if you make $foo a package variable, it gets blown away when
you undef the symbol table entry.  But you shouldn't be using package
variables anyway... so that shouldn't be a problem.

Finally, though, you probably don't need a function that can only be
called once.  Since your web app lives indefinitely, eventually all
the one-time-only functions will have been called, and your app will
be in a steady state.  You might as well get to the steady state as
soon as possible by initializing everything at startup, either in
new() methods or in MyApp.pm (or your config file).  

(Keep in mind that if you put things in MyApp.pm, no classes have been
instantiated before MyApp->setup; and after MyApp->setup, they've
*all* been instantiated.  Inside C<new()> you'll have some subset of
Models/Views/Controllers ready, but I wouldn't count on being able to,
say, do database queries from a Controller's new().  YMMV; in my tests
it looks like the Models load before the Controllers, but I don't know
if that's guaranteed, or just the way the random numbers landed
today.)

Regards,
Jonathan Rockway




More information about the Catalyst mailing list