How to create a url in a controller like HtmlHelper

TL; DR: How do I create a URL in a controller, similar to how I can use HtmlHelper to create URLs in a view?


Problem:

I want to print the controller action url in my controller (because I create my JSON string in my controller, not in the view)

In View I can use $this->Html->url() , but what about the controller?

Should I use a specific constant like APP_DIR + controller name + controller action?)

+7
source share
1 answer

Use the Router class.

 $url = Router::url([ 'controller' => 'Articles', 'action' => 'index', '?' => ['page' => 1], '#' => 'top' ]); 

or the same, but in a more general / simpler scenario:

 $url = Router::url(['controller' => 'Articles', 'action' => 'index']); 

Note: in Cake2.x, β€œArticles” will have lowercase letters.


CakePHP 2.x Router Documentation

CakePHP 3.x 'Creating URL documentation

+30
source

All Articles