【发布时间】:2014-08-11 14:31:42
【问题描述】:
我使用的是 slim php,但这在 slim 中并不是很具体,这在不同 php 框架的路由中很常见,尤其是在使用 rest 应用程序时。
好的,这是可以在博客或归档应用程序中找到的最常见的路径
$app->get('docs(/:year(/:month(/:day)))', function($y=0;$m=0;$d=0) use ($app){
if ($year !== 0 && $month !==0 && $day !== 0) {
// query database with conditions of year, month, day
} else if ($year !== 0 && $month !== 0) {
// query database with conditions of year, month
} else if ($year !== 0) {
// query database with conditions of year
} else {
// query database, return all
}
})
您还想添加get 参数以缩小结果范围,例如limit、offset
$app->get('docs(/:year(/:month(/:day)))', function($y=0;$m=0;$d=0) use ($app){
// additionally you optionally allowed filters like: limit, offset, all
$tmpLimit = $app->request()->get('limit');
$tmpOffSet = $app->request()->get('offset');
$limit = isset($tmpLimit) ? $tmpLimit : 10;
$offset = isset($tmpOffSet) ? $tmpOffSet : 0;
... below add the code previously, and query would change according to if filters(limit,offset) has been set.
})
还有其他解决方案吗?有太多代码告诉我我做得不对。
【问题讨论】:
-
有条件地构造您的查询:
if ($year) $where[] = 'year = ?'; ... sprintf('WHERE %s', join(' AND ', $where)) ...? -
我遇到的这个@deceze 的一个问题是,如果你像你提到的那样通过有条件构造的
$query,我会在绑定变量时遇到问题,就像这样:gist.github.com/8566bba7235a6ba12276.git 那就是如果我只提供年份,或者只提供年份和月份。 -
if ($year) { $where[] = 'year = :year'; $bind['where'] = $year; } ... query($query, $bind) ...?! -
@deceze 如果我发布答案,你介意吗?
-
当然不是。来吧。
标签: php rest if-statement optimization