【发布时间】:2018-02-24 21:12:43
【问题描述】:
我正在尝试在我自己的 mvc 框架中进行路由。像 /controller/action 这样的简单路由在以下情况下正常工作: index.php
$router = new Core\Router();
//添加路由
$router->add('{controller}/{action}');
路由器:
public function add($route, $params = [])
{
// Convert the route to a regular expression: escape forward slashes
$route = preg_replace('/\//', '\\/', $route);
// Convert variables e.g. {controller}
$route = preg_replace('/\{([a-z]+)\}/', '(?P<\1>[a-z-]+)', $route);
// Convert variables with custom regular expressions e.g. {id:\d+}
$route = preg_replace('/\{([a-z]+):([^\}]+)\}/', '(?P<\1>\2)', $route);
// Add start and end delimiters, and case insensitive flag
$route = '/^' . $route . '$/i';
$this->routes[$route] = $params;
}
/**
* Get all the routes from the routing table
*
* @return array
*/
public function getRoutes()
{
return $this->routes;
}
/**
* Match the route to the routes in the routing table, setting the $params
* property if a route is found.
*
* @param string $url The route URL
*
* @return boolean true if a match found, false otherwise
*/
public function match($url)
{
foreach ($this->routes as $route => $params) {
if (preg_match($route, $url, $matches)) {
// Get named capture group values
foreach ($matches as $key => $match) {
if (is_string($key)) {
$params[$key] = $match;
}
}
$this->params = $params;
return true;
}
}
return false;
}
/**
* Get the currently matched parameters
*
* @return array
*/
public function getParams()
{
return $this->params;
}
/**
* Dispatch the route, creating the controller object and running the
* action method
*
* @param string $url The route URL
*
* @return void
*/
public function dispatch($url)
{
$url = $this->removeQueryStringVariables($url);
if ($this->match($url)) {
$controller = $this->params['controller'];
$controller = $this->convertToStudlyCaps($controller);
$controller = $this->getNamespace() . $controller;
if (class_exists($controller)) {
$controller_object = new $controller($this->params);
$action = $this->params['action'];
$action = $this->convertToCamelCase($action);
if (is_callable([$controller_object, $action])) {
$controller_object->$action();
} else {
throw new \Exception("Method $action (in controller $controller) not found");
}
} else {
throw new \Exception("Controller class $controller not found");
}
} else {
throw new \Exception('No route matched.', 404);
}
}
但是当我尝试在我的 index.php 中添加另一条路线时:/controller/id/action 与:
$router->add('{controller}/{id:\d}/{action}');
显示找不到路由异常。我在这里做错了什么。谁能告诉我如何解决这个问题?
【问题讨论】:
-
如果你想一路走下去,请记住大多数路由系统需要容纳相当任意数量的路由,甚至数千个,并且仍然表现良好。这通常意味着将所有路由编译成一个紧凑的状态机,或者一个非常复杂的单数正则表达式。
-
所以生成的正则表达式是:
^(?P<controller>[a-z-]+)\/(?P<id>\d)\/(?P<action>[a-z-]+)$。我认为应该是\d+。无论如何,快速的解决方案 - 以已经工作的路由器为例,我喜欢这个 one -
您尝试路由到的示例 url 是什么?它会抛出“没有匹配的路线”。例外?另外,你能显示你的 removeQueryStringVariables 函数吗,也许它弄乱了 url?
标签: php model-view-controller routes