1
我試圖做一個奇特的路由器,這個想法是:轉換多個字符串成一個多維數組
'{subdomain}.{request type}.{uri}' => '{controller}@{method}'
和我有什麼到目前爲止是這樣的:
路線.PHP
return [
'.GET.' => '[email protected]',
'.GET.user/*' => '[email protected]',
'.GET.user/*/comments' => '[email protected]',
];
Router.php
class Router {
private $routes, $uri, $subdomain;
public function __construct() {
$this->routes = $this->parseRoutes(require 'app/routes.php');
$this->subdomain = $this->getSubdomain();
$this->uri = $this->getUri();
}
private function getSubdomain() {
$url = explode('.', $_SERVER['SERVER_NAME']);
return (count($url) >= 3) ? current($url) : '';
}
private function getUri() {
$uri = preg_replace('#\/{2,}#', '/', urldecode($_SERVER['REQUEST_URI']));
return trim(str_replace(' ', '', $uri), '/');
}
private function parseRoutes($routes) {
$return = [];
foreach($routes as $route => $controller) {
$route = explode('.', $route);
$uri = explode('/', $route[2]);
$return[$route[0]][$route[1]][$route[2]] = $controller;
}
return $return;
}
public function getController() {
}
}
的parseRoutes
方法需要將數組轉換成這樣:
[
'' => [
'GET' => [
'' => '[email protected]',
'user' => [
'*' => [
'' => '[email protected]',
'comments' => '[email protected]'
],
],
],
],
]
我可以得到subdomain
和request type
正常工作,但我不知道如何將URI轉換成類似的格式那。
我不確定你在問什麼。您可以獲取請求的子域並輸入,但是您不知道如何將uri轉換爲這種格式?你有沒有想過哪些部分需要在哪裏以及如何才能到達那裏? –
來自'routes.php'的數組需要轉換成我在底部給出的例子。 – user3117244