现在我的CakePHP博客有这些路由
Router::connect('/blog', array('controller' => 'posts', 'action' => 'index'));
Router::connect('/blog/:slug', array('controller' => 'posts', 'action' => 'view'), array('pass' => array('slug')));
我想让我的帖子url包含日期,如
/blog/2014/05/08/post-slug
我如何设置我的路由/动作来适应这个?当我创建这样的链接
echo $this->Html->link(
$post['Post']['title'],
array('action' => 'view', 'slug'=>$post['Post']['slug'])
);
它会自动添加日期参数?
I got it working
我创建了这个路由
Router::connect('/blog/:year/:month/:day/:slug', array('controller'=>'posts', 'action' => 'view'),
array(
'year' => '[12][0-9]{3}',
'month' => '0[1-9]|1[012]',
'day' => '0[1-9]|[12][0-9]|3[01]',
'pass' => array('year', 'month', 'day', 'slug')
)
我没有创建自己的帮助器,我只是覆盖了AppHelper
中的url方法class AppHelper extends Helper {
public function url($url = null, $full = false) {
if(is_array($url)) {
// add dates to posts
if(isset($url['post'])) {
$url['slug'] = $url['post']['Post']['slug'];
if(!empty($url['post']['Post']['published'])) {
$url['year'] = date('Y', strtotime($url['post']['Post']['published']));
$url['month'] = date('m', strtotime($url['post']['Post']['published']));
$url['day'] = date('d', strtotime($url['post']['Post']['published']));
}
unset($url['post']);
}
}
return parent::url($url, $full);
}
}
然后用
创建链接echo $this->Html->link(
$post['Post']['title'],
array('action' => 'view', 'post'=>$post)
);
In routes:
Router::connect('/blog/*', array('controller' => 'posts', 'action' => 'view'));
然后,在posts控制器中,这样定义动作:
public function view ($year, $month, $day, $slug) {}
至于自动将日期参数添加到链接中,我会编写一个带有函数的助手,该函数将接收帖子的数据数组,然后吐出您想要的链接。