CakePHP hiding action name in URL, while passing a

2019-08-25 13:21发布

问题:

I have such a structure:

  • example.com / MyController / index / MyGoodPage / maximum/
  • example.com / MyController / index / MyBestPage / optimum/
  • example.com / MyController / index / MyFancyPage / lowprice/

But I don't want my visitors to see "index" word, because it doesn't give any more information to him/her. I need my URLs like this:

  • example.com / MyController / MyGoodPage / maximum/
  • example.com / MyController / MyBestPage / optimum/
  • example.com / MyController / MyFancyPage / lowprice/

But to do thisin default Cake-way, I need to create seperate hundereds of actions to handle my situation. I don't want to create them all actions, I need to create one action and then show relevant content regarding to request->params['pass'].

Is it possible?

回答1:

This is a job for Routing: http://book.cakephp.org/2.0/en/development/routing.html and this is actually what is done by default for the core PagesController's display method:

Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

You could do the same for your controller

Router::connect('/controller_name/*', array('controller' => 'controller_name', 'action' => 'index'));


回答2:

You have already selected an answer, but here is a better one.

Router::connect('/controller_name/*', array(...)); as posted above will match anything, so you can no longer access /controller_name/delete or any other method.

You should opt for a less greedy route such as Router::connect('/contorller_name/:something', array(...)); and specify a regex like [maximum|optimum|lowprice] for example.

Doing this you can also specify the something to be passed to the controller and it will be available as $this->request->something