[cgiapp] Re: packages autouse?

Richard Jones ra.jones at dpw.clara.co.uk
Thu Jun 11 19:42:14 EDT 2009


Porta wrote:

> In order to make my Models available on each Controller. Of course, I could
> create a CGI::App package, add all the use lines there and base all my
> Controllers on that package. Sure, less lines to type on each Controller.
> 
> But, every time I create a new Model, I need to make sure I added it on that
> base package. Which I found annoying.
> 
> So, the question is: Does anyone knows a way to *solve* this ( I understand
> it's not really a problem, but more a matter of personal preference ) other
> than having a CA based package including all the packages under Models/ and
> make all the Controllers inherit from that package?

Well, one way is to use a method which returns either a stashed or 
newly-created model object, like this:

package MyApp::Base;

sub model {
   my ($self, $classname) = @_;

   # return stashed package object if it exists:
   if ( my $stashed = $self->stash->{"model::$classname"} ) {
     return $stashed;
   }

   my $package = "MyApp::Model::$classname";

   unless (eval "require $package") {
     $self->error("Unable to load module [$package].");
   }

   # instantiate object
   my $model = $package->new()
         || $self->error("unable to instantiate [$package].");

   # stash for future calls:
   $self->stash->{"model::$classname"} = $model;

   return $model;
}

Then each controller inherits from MyApp::Base (you don't even strictly 
need that level of complexity), and its methods call the model methods 
as eg $self->model('User')->some_method(\%args), where 'User' equates to 
MyApp::Model::User, and contains all the user-related methods. And I 
don't have to worry about adding new Model classes to any list of 
modules, just call them as required. Not sure if that exactly chimes 
with what you wanted though.
-- 
Richard Jones


More information about the cgiapp mailing list