5

What is the difference between $c->uri_for and $c->uri_for_action methods of Catalyst.

Which one to use? And why?

3 Answers3

5

@Devendra I think your examples could be somehow misleading if someone reads them.

uri_for expects path (and not action). It return an absolute URI object, so for example it's useful for linking to static content or in case you don't expect your paths to change.

So for example, let say you've deployed your application on domain example.com and subdir abc (example.com/abc/): $c->uri_for('/static/images/catalyst.png') would return example.com/abc/static/images/catalyst.pn, or for example: $c->uri_for('/contact-us-today') would return example.com/abc/contact-us-today. If you decide later to deploy your application under another subdirectory or at / you'll still end up with correct links.

Let say that your contact-us action looks like: sub contact :Path('/contact-us-today') :Args(0) {...} and you decide later that /contact-us-today should become just /contact-us. If you've used uri_for('/contact-us-today') you'll need to find and change all lines which points to this url. However you can use $c->uri_for_action('/controller/action_name') which will return the correct url.

Dimitar Petrov
  • 667
  • 1
  • 5
  • 16
  • 2
    `uri_for` also works with action i.e. `$c->uri_for('/controller/action_name');` will also work.That's the issue actually.I couldn't find any difference between their (`uri_for` and `uri_for_action`) behavior/working except the `namespace`. Please check and reply. –  Mar 27 '12 at 13:20
  • Though you are right on the point about using `method_name` and not to match direct url. –  Mar 27 '12 at 13:24
  • 1
    Reading the docs seems like that :) I've just never used it like that. Sorry if I've confused you – Dimitar Petrov Mar 27 '12 at 13:37
  • `$c->uri_for_action` is only a small wrapper around `$c->uri_for` that fails if the path does not resolve to a known action. If the 1st argument is an Action object `$c->uri_for` is called anyway and can be used in the first place. You can find that in `lib/Catalyst.pm`. – Daniel Böhmer Sep 25 '17 at 21:49
4

dpetrov_ in #catalyst says:

If the paths are likely to change, uri_for_action is better idea.

daxim
  • 39,270
  • 4
  • 65
  • 132
1

I found below difference between $c->uri_for and $c->uri_for_action

Consider

Othercontroller.pm

__PACKAGE__->config(namespace => 'Hello');

.  
.   
.  

sub bar: Local{

$c->res->redirect($c->uri_for('yourcontroller/method_name'));

$c->res->redirect($c->uri_for_action('yourcontroller/method_name'));

}

Yourcontroller.pm

sub method_name: Local{

print "In Yourcontroller:: method_name"

}

In case of $c->uri_for the url changes to

http://localhost:3000/Hello/yourcontroller/method_name

However for $c->uri_for_action the url changes to

 http://localhost:3000/yourcontroller/method_name

So the namespace gets added in case of uri_for.