开发者

Cakephp internal redirect from controller to another controller

Update: i wrote some wrong statements about the use of header in php; s开发者_StackOverflowo forget that part :)

What i want is to fetch and display a controller's view (with controller's data) from another controller, without have url change in browser.

Some details:

  1. Redirect doesn't do the job because is a direct redirect (via browser)
  2. requestAction doesn't allow me to fetch css and images correctly

I need this thing because i have a controller dispatcher that redirects internally to the other controllers.

I think the only (correct) solution is to use routes.php in /config with Router::connect and there use the logic that was in the dispatcher controller.


ummm... header() is the function to use for a redirect unless the PHP documentation is wrong. (http://php.net/manual/en/function.header.php) The core in cakePHP uses header for the redirect function (see lines 721 - 730 of cake/libs/controller.php).

So I am not certain what you mean "like normal PHP". CakePHP is PHP, it's just built on object oriented code. It's not magic or twisted ways of doing things. So to do a redirect in cake, you can simply use:

$this->redirect(array('controller' => 'my_controller', 'action' => 'my_action'));

And it will call the header() function.

Now. If you are dead set on not using redirect (maybe if you are going to an external site), you can call header() in the code. Just be sure you put the exit(); after the header call:

header('Location: http://call/my/url');
exit();

It will work just the same as redirect. It's just a lot of unnecessary extra work. Keep in mind that using redirect will maintain the domain name and build the URL for you automatically.


In general, connecting URLs to controllers is the job of routes. If your logic is rather complex and normal routes won't cut it, you can even write your own route parser class that does more complex logic (that's all in the manual).

If this routing logic involves database queries or any other sort of controller logic and may lead to very different output for the same URL based on some internal state though, you're making a very RESTless application and I'd submit you should rethink what you're trying to do. Having said that, you can render any view from any controller action using $this->render(). The controller logic for each view could be put in the AppController or possibly (partly) the models to be called from anywhere. So instead of "redirecting" to a different controller, a route just routes to a specific controller action as usual, that action dynamically calls code it needs to call and then renders the view it needs to render.

If you want your app to stay on the same URL but display very different content, you should probably also look into making an AJAX app.

The right solution for you is probably somewhere in between.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜