我的PortfolioController中有以下代码:
function index()
{
$this->set('posts', $this->Portfolio->find('all'));
}
function view ( $id, $slug )
{
$post = $this->Portfolio->read(null, Tiny::reverseTiny($id));
$this->set(compact('post'));
}
Run Code Online (Sandbox Code Playgroud)
但是,为了/view/从URL中删除视图,我在路由中添加了以下内容:Router::connect('/portfolio/*', array('controller' => 'portfolio', 'action' => 'view'));
这会打破索引方法,因为它会通过调用view方法来覆盖它,并显示一个空白视图
我该如何解决?
你准备做什么?(还有什么是$ slug?)
听起来你想要做的是删除动作(或至少是view()动作?)从URL中显示,amirite?有点像默认的pages_controller display()方法 - 静态页面的catch-all动作?
我该如何解决?
好吧,我建议从打破这条路线开始,因为否则它正在按照你的说法去做:
Router::connect('/portfolio/*',
// * is a wildcard matching anything & everything after /portfolio/
array('controller' => 'portfolio',
// and routing to portfolio's view() action, with or w/o required $args to pass
'action' => 'view'));
Run Code Online (Sandbox Code Playgroud)
所以当你调用index()时看到的不是空白视图,它是一个被抑制的致命错误,当index()重新路由到view()并且没有$ id传入第一个arg时会发生这种情况.
注意结束DS.路线顺序很重要; 抓住的第一条规则,胜利.如果省略了url的动作,则以下路径将默认映射到索引,但它们不相同.
// Targets inside the controller (its methods)
Router::connect('/portfolio/',
array('controller' => 'portfolio', 'action' => 'index'));
Run Code Online (Sandbox Code Playgroud)
是不一样的
// Targets the controller
Router::connect('/portfolio',
// Specifies the default controller action, can be whatever
array('controller' => 'portfolio', 'action' => 'index'));
Run Code Online (Sandbox Code Playgroud)
对于你想要做的事情,它应该是
// Targets the controller
Router::connect('/portfolio',
// Routes to 'controller default method' which is index() by Cake default
array('controller' => 'portfolio');
Run Code Online (Sandbox Code Playgroud)
这允许Cake在URL中缺少操作时强制执行自动默认映射到控制器的index().
除了尾随DS和尾随星号之外,它仍然有效.应该捕获index()的相同规则重新路由到view(),这要归功于定位投资组合中所有操作的尾随星号.
因此,Foo的建议不起作用 - >尾随DS +通配符:
Router::connect('/portfolio/',
// the trailing DS changes it to target 'inside portfolio' instead of 'portfolio'
array('controller'=>'portfolio', 'action'=>'index'));
// trailing arbitrary wildcard maps any / all actions directly to view() method
Router::connect('/portfolio/*',
array('controller' => 'portfolio', 'action' => 'view'));
Run Code Online (Sandbox Code Playgroud)
这只是确保投资组合中的所有操作直接映射到投资组合视图()方法(包括/ portfolio/index操作).不要通过go等.任何组合操作都会解析为通配符,无论如何,将整个控制器别名化为该方法.所以你可以将DS从第一条路线上剔除,但是任何以/ portfolio开头的url仍然会路由到view().包括url/portfolio/index.
试试这个:
// catches portfolio/index() without index in the url
Router::connect('/portfolio',
array('controller' => 'portfolio'));
// maps to portfolio/view() without view in url, just /portfolio/integer id
Router::connect('/portfolio/:id',
array('action'=>'view', array('id' => '[0-9]+'));
// routes everything else in portfolio as usual
Router::connect('/portfolio/:action/*',
array('controller'=>'portfolio'));
Run Code Online (Sandbox Code Playgroud)
路线可能很棘手.这是一些链接; HTH.:)
http://bakery.cakephp.org/articles/Frank/2009/11/02/cakephp-s-routing-explained
http://book.cakephp.org/view/46/Routes-Configuration