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

Jonathan Rockway jon at jrock.us
Sun Sep 3 08:59:30 CEST 2006


> This works although if feels like a hack that left one
> of my Java peers snickering as well as incurs a minor
> penalty for each request.
>   

Yeah, please don't do that. :)

> sub COMPONENT
>   

So does new() not work?  That's what I would use for initializing my class.

All your Models/Views/Controllers are instantiated at app start time by
Catalyst.  If this is when you want config to happen, use new().  You
can also use c->config->{MyApp::Controller::Whatever}->{service} =
$c->model(...) inside MyApp.pm.  (And then use Class::Accessor inside
your class; but that's not required.)

> {
>   my $self	= shift->SUPER::new(shift @_);
>   my ($c)	= @_;
> 	
>   my $service	= 'feedrolls';
>
>   $self->{service} =  
>    $c->model('db::services::services');
> 	
>   return $self;
> }
>   
You're shifting a few too many times, I think.  Try:

my $self = shift;
$self = $self->NEXT::new(@_);
my $c = shift;

...

instead.  Note NEXT instead of SUPER; Catalyst uses NEXT (at the
moment).  You might also like Class::C3 or Catalyst::Plugin::C3 instead.

As a last resort, if you want the method to be called the first time
begin() is called, you can simply remove your begin from the symbol
table the first time through:

sub begin {
   ...
   undef $PACKAGE::{begin}
}

I haven't tried this, but it should work.  (I tested it inside main::,
and I had to type main instead of __PACKAGE__.  You'll probably have to
do the same.  Also, be aware of the side effects by reading the manual
page.)

Let us know how it goes.

Manual pages to read:
* NEXT
* Class::C3
* "Symbol Tables" in perlmod

Regards,
Jonathan Rockway



More information about the Catalyst mailing list