Cakephp 带命名参数的路由
我有一个包含命名参数的URL,我想将其映射到一个更用户友好的URL 以以下URL为例: /videos/index/sort:published/direction:desc 我想将其映射到更友好的URL,如: /视频/最近的 我试过在路由器上设置,但不起作用 来自路由器的代码示例:Cakephp 带命名参数的路由,cakephp,parameters,routing,routes,named,Cakephp,Parameters,Routing,Routes,Named,我有一个包含命名参数的URL,我想将其映射到一个更用户友好的URL 以以下URL为例: /videos/index/sort:published/direction:desc 我想将其映射到更友好的URL,如: /视频/最近的 我试过在路由器上设置,但不起作用 来自路由器的代码示例: Router::connect( '/videos/recent/*', array('controller' => 'videos', 'action' => 'index'),
Router::connect(
'/videos/recent/*',
array('controller' => 'videos', 'action' => 'index'),
array('sort' => 'published', 'direction' => 'desc'
));
这不管用。以下也不起作用:
Router::connect(
'/videos/recent/*',
array('controller' => 'videos', 'action' => 'index', 'sort' => 'published', 'direction' => 'desc'));
有什么想法吗?使用get args
让路由工作的最简单方法是避免所有命名参数。使用以下易于实现的分页:
通过这种方式,当您加载/videos/recent
时,您应该会发现它包含以下形式的URL:
/videos/recent?page=2
/videos/recent?page=3
而不是(由于路由不匹配)
但是如果你真的想使用命名参数
您需要更新路由定义-路由配置中没有页面:
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'index',
'sort' => 'published',
'direction' => 'desc'
)
);
因此,如果有一个名为parameter的页面(paginator助手生成的所有URL都有该页面),则路由将不匹配。您应该能够通过将页面
添加到路线定义中来解决此问题:
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'index',
'sort' => 'published',
'direction' => 'desc',
'page' => 1
)
);
尽管它可以工作,但您可能会发现它很脆弱。让我们看看[Router::connect documentation](路由是将请求URL连接到应用程序中对象的一种方式) 路由是将请求URL连接到应用程序中对象的一种方式 所以,它是将url映射到对象,而不是url映射到url 您有两种选择: 使用路由器::重定向 诸如此类:
Router::redirect( '/videos/recent/*', '/videos/index/sort:published/direction:desc');
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'recent'
)
);
但这似乎不是你想要的
使用路由器::连接
使用普通路由器::connect,它会将url连接到一些操作,这些操作会产生适当的作用域。诸如此类:
Router::redirect( '/videos/recent/*', '/videos/index/sort:published/direction:desc');
Router::connect(
'/videos/recent/*',
array(
'controller' => 'videos',
'action' => 'recent'
)
);
在视频控制器中
public function recent() {
$this->request->named['sort'] = 'published';
$this->request->named['direction'] = 'desc';
$this->index();
}
它是有效的,我看到了这样的用法,但不确定,这也会让你满意
至于我,我喜欢普通命名的cakephp参数。如果这样的范围(published和desc)是您的默认状态,只需在索引操作中对默认状态进行编码。对于以上情况,我认为使用普通命名参数是正常的 您是否尝试了
Router::connect('/videos/recent/*',array('controller'=>'videos','action'=>'index'),array('pass'=>array('sort','direction'),'sort'=>'published','direction'=>'desc'))代码>?是的,刚试过,不起作用。就像我上面的例子一样,它路由到正确的控制器和操作,并显示页面,但排序实际上不起作用。第二个选项不起作用。我开始觉得没有一个好的解决办法。我可以试试传递参数。谢谢。你需要看看例如。不过,请记住,我一直使用cake,并且我是核心团队成员,正如前面提到的,您最好不要使用命名的args。命名的args可能会被弃用并在将来的(主要)cake版本中删除。