CakePHP - Quick way to get /controller/action path?
Asked Answered
B

3

11

Is there a Controller property that will allow me to get just /controller/action from the URL without any additional parameters there might be?

At the moment I am having to join $this->name . '/' . $this->action.

Broz answered 27/7, 2011 at 12:25 Comment(2)
What do you need it for?Frediafredie
To pass to my login page as a redirectBroz
F
17

You don't want to construct the string /users/login, you want the URL that corresponds to the login action of your users controller (for example). That is not necessarily the same as /users/login, and you should not hardcode it!

To get a URL that will lead to a controller action, use reverse routing:

Router::url(array('controller' => 'users', 'action' => 'login'));
//or
Router::url(array('controller' => $this->name, 'action' => $this->action));

Yes, that's even longer, but it's the correct way to do it. If one day you decide you want the login URL to be /login or /members/entrance instead of /users/login, you only need to define an appropriate route in routes.php without rewriting all your hardcoded links.

Frediafredie answered 27/7, 2011 at 12:54 Comment(0)
A
4
$this->here

Available in view and controller. Minor note: It's getting removed in 2.0.

Avraham answered 27/7, 2011 at 12:29 Comment(3)
I think $here includes any additional URL parameters.Broz
@Broz Which as you want to use it for a login redirect, I would say are quite relevant. If you just want the controller and action then just join the controller and action like you have been!Avraham
No, I don't want the extra parameters. Thanks, I'll just carry on with joining the controller/action.Broz
I
2

It is also possible to use HtmlHelper::url method in 2.x.

$this->Html->url(array(
  "controller" => "controller",
  "action" => "action",
  "parameter"
));

For CakePHP 3.x, UrlHelper is a good choice:

$this->Url->build([
  "controller" => "controller",
  "action" => "action",
  "parameter"
]);

Both examples produce

/controller/action/parameter
Icao answered 24/10, 2014 at 16:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.