[Catalyst] Re: Private Chained Actions?

Aristotle Pagaltzis pagaltzis at gmx.de
Fri Jun 20 23:27:45 BST 2008


* Jonathan Rockway <jon at jrock.us> [2008-06-20 22:20]:
> >>    sub hello_setup : Private {
> >>      my ($self, $c) = @_
> >>      $c->stash->{setup} = 'done';
> >>    }
> >>
> >>    sub hello : Private {
> >>      my ($self, $c) = @_
> >>      $c->forward('hello_setup'); # <---------
> >>      $c->res->body('hello! setup is ' . $c->stash->{setup});
> >>    }
> >>
> >>    sub index : Path : Args(0) {
> >>      my ($self, $c) = @_
> >>      $c->detach('hello');
> >>    }
> 
> Yeah, that's ugly.  What you really want are method modifiers:
> 
>     package MyApp::Controller::Foo;
>     use Moose;
>     BEGIN { extends 'Catalyst::Controller' };
>     
>     sub main_page :Path Args(0) {
>         my ($self, $c) = @_;
>         $self->hello($c);
>     }
>     
>     sub hello {
>         my ($self, $c) = @_;
>         $c->res->body('hello! setup is'. $c->stash->{setup});
>     }
>     
>     before hello => sub {
>         my ($self, $c) = @_;
>         $c->stash->{setup} = 'done';    
>     };
>     
>     1;

That’s even uglier. Imagine there isn’t just `hello` but half a
dozen other methods all sharing the same setup. So the setup code
is one or two screens down the source file. Now when you look at
`hello` you have absolutely no indication whatsoever that there
might be other code running before it. The only sane way to do
this would go something like this:

    package MyApp::Controller::Foo;
    use Moose;
    BEGIN { extends 'Catalyst::Controller' };
    
    sub main_page :Path Args(0) {
        my ($self, $c) = @_;
        $self->hello($c);
    }

    sub hello_setup {
        my ($self, $c) = @_;
        $c->stash->{setup} = 'done';    
    }
    
    before hello => \&hello_setup;
    sub hello {
        my ($self, $c) = @_;
        $c->res->body('hello! setup is'. $c->stash->{setup});
    }
    
    1;

By naming the setup method you can also avoid having to apply
the modifier to all of the methods at once.

Note that using method modifiers instead of Cat dispatch means
that the Catalyst::Stats breakdown of a request will be coarser.

Regards,
-- 
Aristotle Pagaltzis // <http://plasmasturm.org/>



More information about the Catalyst mailing list