【发布时间】:2016-10-12 04:54:43
【问题描述】:
假设我有这个动作:
public function index_by_date($year = NULL, $month = NULL, $day = NULL) {
if($year && $month && $day) {
//Posts of day
}
elseif($year && $month) {
//Posts of month
}
elseif($year) {
//Posts of year
}
else {
//Exception...
}
}
这显示了一天的帖子(2016 年 6 月 11 日的所有帖子):mysite.com/posts/2016/06/11
这显示了整月的帖子(2016 年 6 月的所有帖子):mysite.com/posts/2016/06
这显示了一整年的帖子(2016 年的所有帖子):mysite.com/posts/2016
我认为这很清楚。
现在我想为所有这些情况编写一条路线。那么,第二个和第三个参数应该是可选的。
我尝试过类似的方法,但这不起作用:
$routes->connect('/posts/:year/:month/:day',
['controller' => 'Posts', 'action' => 'index_by_date'],
[
'year' => '[12][0-9]{3}',
'month' => '(0[1-9]|1[012])?',
'day' => '(0[1-9]|[12][0-9]|3[01])?',
'pass' => ['year', 'month', 'day']
]
);
怎么办?
编辑 目前,这是我能做的最好的:
路线:
$routes->connect('/posts/:date',
['controller' => 'Posts', 'action' => 'index_by_date'],
[
'date' => '\d{4}(\/\d{2}(\/\d{2})?)?',
'pass' => ['date']
]
);
行动:
public function index_by_date($date = NULL) {
list($year, $month, $day) = array_merge(explode('/', $date), [NULL, NULL, NULL]);
if($year && $month && $day) {
//Posts of day
}
elseif($year && $month) {
//Posts of month
}
elseif($year) {
//Posts of year
}
else {
//Exception...
}
}
有没有更好的方法来做到这一点?
【问题讨论】:
标签: cakephp routes cakephp-3.0