How to Create a URL in Controller like HtmlHelper
Asked Answered
C

1

10

TLDR: How can I create a URL in the Controller similar to how I can use the HtmlHelper to create URLs in a View?


Problem:

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

In a View, I can use $this->Html->url(), but what about in a Controller?

Should I use defined constant like APP_DIR + Controller name + Controller action?)

Cancer answered 11/8, 2012 at 14:17 Comment(0)
D
37

Use the Router class.

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

or the same thing, but in a more common/simple scenario:

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

Note: in Cake2.x, "Articles" would be lowercase.


CakePHP 2.x Router documentation

CakePHP 3.x 'Generating URLs' documentation

Double answered 11/8, 2012 at 14:57 Comment(1)
Remember to use the routing class: use Cake\Routing\Router;Titos

© 2022 - 2024 — McMap. All rights reserved.