2017-11-27 9 views
0

現在、私のRouterクラスでは、私はこの機能があります。ダイナミックパラメータを使用したURLルーティング?

public function findRouteForRequestURI($uri) 
{ 
    if(isset($this->routes[$uri])) { 
     $match['class'] = $this->routes[$uri]['controller']; 
     $match['action'] = $this->routes[$uri]['action']; 

     if(isset($this->routes[$uri]['params'])) { 
      // Not sure about this part yet 
      if ($this->routes[$uri]['params']) { 
       $uriSegments = explode('/', $uri); 
       $match['params'] = $uriSegments; 
      } 
     } 
     return $match; 
    } 
    return false; 
} 

をそして、私はホワイトリストルートのこの配列、$this->routesあります

private $routes = array(
    '/'  => array(
     'controller' => 'controllers\product\Product', 
     'action' => 'getAllProducts' 
    ), 
    '/cart' => array(
     'controller' => 'controllers\cart\Cart', 
     'action'  => 'getCartDetails' 
    ), 
    '/product/\d+/' => array(// Not sure how to do this for routes with dynamic parameters 
     'controller' => 'Product', 
     'action' => 'getProductDetails', 
     'params' => true 
    ) 
); 

を私の問題は、私はどのように私は希望わからないです動的パラメータを持つURLのホワイトリストに登録されたルートを作成します。 がありたいとします。セグメント12は任意の数値にすることができます。

/product/:id実際にはコントローラProductを、getProductDetailsという1つのパラメータ(productId)を使用する方法で検索しようとします。ただし、ここには表示されていません。検索およびインスタンス化の部分は、私のDispatcherクラスにあります。

答えて

0

あなたは、動的にルートを一致させるために正規表現を使用できますが、可能であればオーバーヘッドを避けるために、最初の場所であなたのシンプルなISSETを維持したいと思う:

if(!isset($this->routes[$uri])) { 
    // this could also be moved to a subroutine 
    // like $this->handleDynamicRoute($uri); 
    $dynamicRoutes = $this->getDynamicRoutes(); 

    foreach ($dynamicRoutes as $route) { 
     if (preg_match($route['pattern'], $uri) { 
      $uriSegments  = explode('/', $uri); 
      $match['params'] = (int) array_pop($uriSegments); 
      $uri    = "/" . $uriSegments[0]; 
     } 
    } 
} 

// proceed as before... 
$match['class'] = $this->routes[$uri]['controller']; 
$match['action'] = $this->routes[$uri]['action']; 

我々はすべてを整理するために、この小さな番号を持っています正規表現パターンを持つルート。これを行うには、より効率的な方法はおそらくあります:

'/product' => [ 
    'controller' => 'Product', 
    'action'  => 'getProductDetails', 
    'pattern' => '/product/\d+/' 
] 
+0

ありがとう:これに

コンサートで
private function getDynamicRoutes() { $dynamicRoutes = []; foreach ($this->routes as $route) { if (isset($route['pattern'])) { $dynamicRoutes[] = $route; } } return $dynamicRoutes; } 

あなたのルート配列少しクリーナーを保つことができます!しかし、ちょうど1つの質問ですが、なぜあなたは '$ uri'を最後に設定しましたか? ''/''で設定してください。 $ uriSegments [0]; ' – herondale

+0

これまでのように、配列からアクションとコントローラを取得できるように、答えを編集しました。お役に立てて嬉しいです!私はあなたが私の答えを受け入れることができれば感謝します。 – larsAnders

関連する問題