CakePHP前缀路由 [英] CakePHP Prefix Routing
问题描述
如何进行
domain.com/api/somecontroller/someaction
和
domain.com/somecontroller/someaction
指向同一控制器操作:
class somecontroller {
function someaction() {
}
}
注意:我不想只重新路由一个动作。但我想重新路由domain.com/api/*的所有路由到没有'api'前缀的相应的URL。
Note: I don't want to re-route just one action. But I want to reroute all routes of domain.com/api/* to their corresponding URLs without the 'api' prefix.
例如:
domain.com/api/controller -> domain.com/controller
domain.com/api/controller/action -> domain.com/controller/action
domain.com/api/controller/action/param -> domain.com/controller/action/param
domain.com/api/controller/action?key=val -> domain.com/controller/action?key=val
我试图在routes.php中添加以下内容:
I tried adding the following in routes.php:
Router::connect('/api', array('controller'=>'index', 'action'=>'index'));
Router::connect('/api/:controller', array('action'=>'index'));
Router::connect('/api/:controller/:action');
Router::connect('/api/:controller/:action.:ext');
它适用于定义的规则。但我似乎不包括所有的情况。当您使用网址参数或插件和其他高级网址时,它会失败。
It works fine for the rules defined. But I doesn't seem to cover all scenarios. Like it fails when you use URL params, or plugins and other advanced URLs.
是否有更简单的方法来完成我想要的任务?
Is there an easier way of accomplishing the task that I want?
推荐答案
您不需要这4条规则,因为您可以在CakePHP的路由系统中使用通配符(*)。
You do not need those 4 rules you have as you can use wildcards (*) in CakePHP's routing system.
所以在app / Config / routes.php中只添加一个规则来覆盖你想要的一切。
So in app/Config/routes.php add only one rule which will cover everything you want ..
Router::connect('/api/:action/*', array('controller' => 'mycontroller'));
然后,每个请求像 http://domain.com/api/someaction ,结果会显示在 http://domain.com/mycontroller/someaction 。
Then, every request that is like http://domain.com/api/someaction, will end up at http://domain.com/mycontroller/someaction.
在我的代码示例中,唯一需要更改的是控制器的名称,我有上面指定的 mycontroller 。
The only thing you need to change in my code example is the name of the controller, I have mycontroller specified above.
您看到的:action 部分基本上是一个占位符, , * 是通配符。
the :action part you see is basically a placeholder for any actions specified in the request and the * is a wildcard.
这篇关于CakePHP前缀路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!