2016-01-15 126 views
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]' 
       ], 
      ], 

     ], 
    ], 
] 

我可以得到subdomainrequest type正常工作,但我不知道如何將URI轉換成類似的格式那。

+0

我不確定你在問什麼。您可以獲取請求的子域並輸入,但是您不知道如何將uri轉換爲這種格式?你有沒有想過哪些部分需要在哪裏以及如何才能到達那裏? –

+0

來自'routes.php'的數組需要轉換成我在底部給出的例子。 – user3117244

回答

0
protected $controller = 'home'; 
protected $method = 'index'; 
protected $params = []; 
public function __construct(){ 
this->parseUrl(); 
// also add if statements to check if controller, method exist 

// CHECK IF PARAMETERS EXIST, IF YES, GET ARRAY OF PARAMENTERS, OTHERWISE SET EMPTY ARRAY 
$this->params = $url ? array_values($url) : []; 
call_user_func_array([$this->controller, $this->method], $this->params); 

} // end of constructor 
// SPLITTING URL INTO ARRAY (url[0]/url[1]/url[2]/...) 
// A.K.A.(controller/method/property1/property2/...) 
public function parseUrl(){ 
if(isset($_GET['url'])){ 
    return $url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL)); 
} // end of if 
} // end of function parseUrl 
+0

我不認爲這將有助於OP。 –