[Catalyst] Forward on to other actions after removing first path segment?

Ben van Staveren benvanstaveren at gmail.com
Tue Nov 16 17:24:22 GMT 2010


> Request-URI: /2010-11-15/foo
>
> * MyApp::_date is triggered
> * Removes the date from the first path segment and stashes it
> * Forwards to MyApp::Foo::index as if it was a fresh request and the 
> date path segment was never there (except it is, in the stash).
I just realised I made a little mistake too, given that the chained 
action indeed triggers off something like /date - you could chain the 
date capture bit to / (PathPart '') but that might get you some 
unexpected results.

There are 2 solutions:

1) Use the 'default' action:

sub default :Private {
  my $self = shift;
  my $c = shift;
  my @requested_uri = (@_);
 
  my $potential_date = shift(@requested_uri);
  if($potential_date =~ /(\d{4}-\d{2}-\d{2})/) {
    $c->stash->{date} = $1;
    my $bit_after_date = shift(@requested_uri);
    my @remainder = @requested_uri;
    $c->detach('Your::Controller', $bit_after_date, [ @remainder ]);
  } else {
     # 404?
  }
}

The above very much expanded to make clear what happens. If I go to the 
URI /2010-10-10/foo, it strips the date off and stashes it, and then 
forwards to Your::Controller->foo() - if I go to the URI 
/2010-10-10/foo/bar it will dispatch to Your::Controller->foo as well, 
but passes 'bar' as first argument (basically assuming that 'foo' is a 
:Local action)

Another option is to muck with the Catalyst internals a bit, I think 
there's a hook of sorts you can override in your controller that lets 
you examine the URI before it's dispatched to a controller, and it also 
lets you *modify* the URI before dispatching. Internal rewrite rules, as 
it were.

Wait, third option: use rewrite rules, as you mentioned, because in 
theory this means that if a date is there, it acts the same as if there 
is no date present, and you can always examine $ENV{DATE} to see if it's 
there.

The above might not be the best ways to get done what you want, but it's 
the best I can come up with late at night :) Maybe some other people can 
pitch in?

-- 
Ben van Staveren
phone: +62 81 70777529
email: benvanstaveren at gmail.com




More information about the Catalyst mailing list