В течение нескольких лет я работаю над своей собственной облегченной средой MVC для PHP. Который я могу в какой-то момент выпустить под лицензией с открытым исходным кодом.
Вот что я использовал для обработки маршрутов:
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;
}
$ routs - это переданный массив, отформатированный так:
$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.