这并不能明确回答您的问题,但我只需通过使用路径来解决问题,从而抛开整个复杂性:
// Whitelist other public actions in BlogPostsController first,
// so they're not caught by the catch-all slug rule.
// This whitelists BlogPostsController::other() and ::actions(), so
// the URLs /blog/other/foo and /blog/actions/bar still work.
Router::connect('/blog/:action/*',
array('controller' => 'blog_posts'),
array('action' => 'other|actions'));
// Connect all URLs not matching the above, like /blog/my-frist-post,
// to BlogPostsController::single_post($slug). Optionally use RegEx to
// filter slug format.
Router::connect('/blog/:slug',
array('controller' => 'blog_posts', 'action' => 'single_post'),
array('pass' => array('slug') /*, 'slug' => 'regex for slug' */));
请注意,在撰写本文时,上述路径仅依赖于最近的一个bug修复,并将其合并到Cake中(参见
http://cakephp.lighthouseapp.com/projects/42648/tickets/1197-routing-error-when-using-regex-on-action
). 有关更兼容的解决方案,请参阅此帖子的编辑历史记录。
至于
single_post
方法可以直接访问:我不会
/blog/:slug
路线捕捉器
全部的
以开头的URL
/blog/
,它会抓住的
/blog/single_post
然后调用
BlogPostsController::single_post('single_post')
. 然后,您将尝试找到一个带有“single_post”的帖子,这个帖子可能不存在。在这种情况下,您可以抛出404错误:
function single_post($slug) {
$post = $this->BlogPost->get_post_by_slug($slug);
if (!$post) {
$this->cakeError('error404');
}
// business as usual here
}
错误处理:完成。