[Catalyst] Various ways to use c.uri_for

Octavian Rasnita orasnita at gmail.com
Sat Jan 9 14:16:46 GMT 2010


From: "Kiffin Gish" <kiffin.gish at planet.nl>

>I noticed that in certain examples depending on the coder, sometimes the
> following format is used:
>
>    c.uri_for(c.controller('Users').action_for('list'))
>
> and other times this fomat:
>
>    c.uri_for('/users/list')
>
> What's the difference and is there an advantage of using one or the
> other?
>
> Thanks alot in advance.
>
> -- 
> Kiffin Gish <Kiffin.Gish at planet.nl>


In the first case you can provide the name of the action and not the URL 
that dispatches to it.

The advantage of the first one is that you may want to change the way the 
URL looks like and in that case those links will work.

For example, say that you have the following action:

package MyApp::Controller::Users;

sub lst : Path('list' {}

You can access the lst action by using the following:

c.uri_for('/users/list')
and
c.uri_for(c.controller('users').action_for('lst')

In the future, if you will want to change some things and access the list of 
users with an URL like

/users/something-else

the first way won't work, and you will need to check all the templates and 
change it, while the second will work fine, and it will generate the correct 
URL to the action lst.

It could be helpful to have shortcuts for the second way of creating URLS, 
something like...

c.url_query('controller_name', 'action_name', param1, param2)

We can put a url_query subroutine in MyApp.pm that looks like the one below 
(although I don't know if it works in all the cases - chains), but it could 
be helpful to have such a thing in the core:

sub url_query {
  my ($c, $controller, $action, @params) = @_;
  return $c->uri_for($c->controller($controller)->action_for($action), 
@params)->path_query;
}

Octavian




More information about the Catalyst mailing list