【发布时间】:2011-12-06 22:15:57
【问题描述】:
几年来,我一直致力于开发自己的 PHP 轻量级 MVC 框架。我可能会在某个时候根据开源许可发布。
这是我一直用来处理路线的:
function routes($routes, $uriPath) {
// Loop through every route and compare it with the URI
foreach ($routes as $route => $actualPage) {
// Create a route with all identifiers replaced with ([^/]+) regex syntax
// E.g. $route_regex = shop-please/([^/]+)/moo (originally shop-please/:some_identifier/moo)
$route_regex = preg_replace('@:[^/]+@', '([^/]+)', $route);
// Check if URI path matches regex pattern, if so create an array of values from the URI
if(!preg_match('@' . $route_regex . '@', $uriPath, $matches)) continue;
// Create an array of identifiers from the route
preg_match('@' . $route_regex . '@', $route, $identifiers);
// Combine the identifiers with the values
$this->request->__get = array_combine($identifiers, $matches);
array_shift($this->request->__get);
return $actualPage;
}
// We didn't find a route match
return false;
}
$routes 是一个传递的数组,格式如下:
$routes = array(
// route => actual page
'page/:action/:id' => 'actualPage',
'page/:action' => 'actualPage',
)
$uriPath 是没有前导正斜杠的 URI 路径,例如页面/更新/102
在我的页面控制器中,我可以像这样访问路由信息:
echo $this->request->__get['action'];
// update
echo $this->request->__get['id'];
// 102
我的问题本质上是“这可以简化或优化吗?”。特别强调简化正则表达式以及 preg_replace 和 preg_match 调用的数量。
【问题讨论】:
-
您有性能问题吗?看看这里kohanaframework.org/3.2/guide/api/Route
标签: php regex model-view-controller routes