我正在使用Cakephp 2+,我有一个名为"帖子"的模型,帖子可以是不同类型的,例如 - 博客文章,消息等。
在配置/路由.php中,如何设置路由以使我有/posts/12/post-title
或/blog/14/blog-title
?
目前我有这个:
Router::connect('/:type/add', array('controller' => 'posts', 'action' => 'add'),
array('pass' => array('type')));
Router::connect('/:type/:action', array('controller' => 'posts'),
array('pass' => array('type')));
# Custom posts router
Router::connect('/:type/:id/:slug',
array('controller' => 'posts', 'action' => 'view'),
array('pass' => array('type', 'id', 'slug'), 'id' => '[0-9]+'));
但问题是,然后每个URL都使用它,所以cakephp认为我的用户个人资料页面应该查看我的帖子控制器,因为它认为我正在传递一个:type -
。
#View Profile
Router::connect('/profile/:id', array('controller' => 'users', 'action' => 'view'),
array('pass' => array('id'), 'id' => '[0-9]+'));
有谁知道正确执行此操作的方法?非常感谢
首先,你的路由顺序很重要,如果多个路由将匹配一个URL,则将处理第一个匹配的路由
接下来,您可以通过在 Router::connect() 的最后一个参数中为 "type" 键设置正则表达式来限制 "what" 将被视为"类型",就像对 'id' 所做的那样。您可以在正则表达式中包含所有有效类型,或者在正则表达式中添加排除值的"负"部分,例如控制器名称
像这样:
Router::connect(
'/:type/:action',
array(
'controller' => 'posts',
),
array(
/**
* Custom type:
* only allow 'post', 'blog' or 'message' as type here
* to prevent overlapping with 'controllers'
*/
'type' => '(post|blog|message)',
// Define what should be passed to the 'view' action as arguments
'pass' => array('type'),
/**
* Optionally, define what parameters should be automatically preserved
* when creating URLs/links
*/
'persist' => array('type'),
)
);
Router::connect(
'/:type/:id/:slug',
array(
'controller' => 'posts',
'action' => 'view',
),
array(
/**
* Custom type:
* only allow 'post', 'blog' or 'message' as type here
* to prevent overlapping with 'controllers'
*/
'type' => '(post|blog|message)',
'id' => '[0-9]+',
// Define what should be passed to the 'view' action as arguments
'pass' => array('type', 'id', 'slug'),
/**
* Optionally, define what parameters should be automatically preserved
* when creating URLs/links
*/
'persist' => array('type'),
)
);