【发布时间】:2017-11-05 14:59:37
【问题描述】:
我尝试用 PHP 构建一个路由系统。我对可更改的 URL 有疑问。
private $routes = array(
"blog" => array("Blog", "GetAll"),
"/blog\/*/" => array("Blog", "GetOne"),
);
private $query;
public function __construct()
{
$this->query = filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_URL);
}
public function SendAction()
{
$route = array();
if (array_key_exists($this->query, $this->routes)) {
$route['controller'] = $this->routes[$this->query][0];
$route['action'] = $this->routes[$this->query][1];
$route['params'] = $this->routes[$this->query][2];
} else {
$route['controller'] = "Error";
$route['action'] = "Main";
$route['params'] = array();
}
return $route;
}
问题在于包含abc/my_custom_variable_or/slug的网址。
我需要获取my_custom_variable_or 和slug 并将它们放入params['fdsaf'] 以便我可以在我的控制器中使用它
我找到了 else if 的临时解决方案,例如:else if (preg_match("/blog\/*/", $this->query)) .... explode() 等...
为了让我的系统更灵活,我需要在$routes 数组中创建一些东西。路由数组将是一个不同的文件。
===示例输入和预期结果===
网址:博客
$route['controller'] = Blog
$route['action'] = GetAll
$route['params'] = array()
网址:blog/my-first-post
$route['controller'] = Blog
$route['action'] = GetOne
$route['params'] = array('slug' => 'my-first-post')
网址:blog/user/martin/page2(page2 是可选的)
$route['controller'] = Blog
$route['action'] = GetUserPost
$route['params'] = array('slug' => 'martin')
【问题讨论】:
-
我编辑问题并添加示例输入和预期结果
标签: php arrays regex model-view-controller routing