[Mpls-pm] Using Mason's $m from within a perl module

Lee Carmichael lecar_red at yahoo.com
Thu Dec 1 15:30:10 PST 2005


Hello Dave,

> package Foo;
> 
> 
> > our $m =  HTML::Mason::Request::instance;
> >
> sub login_required
> > {
> >     unless ($m->session->{'userid'}) {
> >         $m->comp('login.mhtml');
> >         $m->abort;
> >     }
> > }
> >
> 
> but this always fails saying that $m isn't
> instantiated.  Everything works
> fine if I define the $m locally within each sub, but
> that gets annoying.  I
> thought our should scope to the entire package. 
> What's the propper way to
> take this on?

I think the 'our' is making the variable exist but
Perl sets this up at module load time. At that point,
there isn't request so the 'instance' method return
'undef' (per
http://masonhq.com/docs/manual/Request.html#accessor_methods
). 

When you stick it inside the 'login_required' sub, it
grabs an instance at runtime, after it has been
created so everything is ok. 

You probably want to add a 'init' method to this
package to do something like:

package Foo;

our $m;

sub init { $m = HTML::Mason::Request->instance(); } 

sub login_required { ... }

I haven't tested this but I think it will do what you
want. 

Please note, that this will cause a copy of that
request instance inside the package var '$m' until the
next request. You probably don't really want to do it
leave this around. You could add a 'cleanup' sub like:

sub cleanup { $m = undef; } 

These additional subs can be called in the user of
this module like: 

Foo::init();

Foo::login_required if ($some_condition);

Foo::cleanup();

I'm not sure what the code that calling this looks
like so I cannot really make any other recommendations
besides you might want to make Foo an object which can
automate the cleanup for you. Just in case, you end up
somewhere where 'cleanup' cannot be called from. Also,
you might want to look into 'MasonX::WebApp' since it
provides a slick framework for doing stuff like this. 

Good Luck,

Lee



		
__________________________________________ 
Yahoo! DSL – Something to write home about. 
Just $16.99/mo. or less. 
dsl.yahoo.com 



More information about the Mpls-pm mailing list