OSDN Git Service

More rewriting..
authorDanny van Kooten <dannyvankooten@gmail.com>
Sun, 15 Jan 2012 21:45:24 +0000 (22:45 +0100)
committerDanny van Kooten <dannyvankooten@gmail.com>
Sun, 15 Jan 2012 21:45:24 +0000 (22:45 +0100)
Router.php
example.php

index 96ce7a0..04495a8 100644 (file)
@@ -16,30 +16,12 @@ class Router {
     private $namedRoutes = array();
 
     /**
-     * Boolean whether a route has been matched.
-     * @var boolean
-     */
-    private $routeMatched = false;
-
-    /**
-     * The matched route. Contains an array with controller, action and optional parameter values.
-     * @var array 
-     */
-    private $matchedRoute = array();
-
-    /**
      * The base REQUEST_URI. Gets prepended to all route url's.
      * @var string
      */
     private $basePath = '';
     
     /**
-    * Temporary variable to store route arguments for usage inside the regex callback
-    * @var array
-    */
-    private $arguments = array();
-
-    /**
      * Set the base url - gets prepended to all route url's.
      * @param string $base_url 
      */
@@ -94,20 +76,23 @@ class Router {
         $this->routes[] = $route;
     }
 
-    public function execute() {
-
+    public function matchCurrentRequest() {
         $requestMethod = (isset($_POST['_method']) && ($_method = strtoupper($_POST['_method'])) && in_array($_method,array('PUT','DELETE'))) ? $_method : $_SERVER['REQUEST_METHOD'];
 
-        $requestUrl = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
-        $requestUrl = rtrim($requestUrl, '/');
+        return $this->match($_SERVER['REQUEST_URI'], $requestMethod);
+    }
+
+    public function match($requestUrl, $requestMethod = 'GET') {
+        
+        $matched = false; 
                 
         foreach($this->routes as $route) {
             
             // if route has been given a name, store it in the namedRoutes array
             if($route->getName() !== null) { $this->namedRoutes[$route->getName()] = $route; }
 
-            // don't do anything if a route has already been found
-            if($this->routeMatched) continue;
+            // don't do anything if a route has already been matched
+            if($matched) continue;
 
             // compare server request method with route's allowed http methods
             if(!in_array($requestMethod, $route->getMethods())) continue;
@@ -115,6 +100,8 @@ class Router {
             // check if request url matches route regex. if not, return false.
             if (!preg_match("@^".$route->getRegex()."*$@i", $requestUrl, $matches)) continue;
 
+            $params = array();
+
             if (preg_match_all("/:(\w+)/", $route->getUrl(), $argument_keys)) {
 
                 // grab array with matches
@@ -123,7 +110,7 @@ class Router {
                 // loop trough parameter names, store matching value in $params array
                 foreach ($argument_keys as $key => $name) {
                     if (isset($matches[$key + 1]))
-                        $this->arguments[$name] = $matches[$key + 1];
+                        $params[$name] = $matches[$key + 1];
                 }
 
             }
@@ -136,14 +123,15 @@ class Router {
                 $target = explode('/', ltrim(str_replace($this->basePath, '', $requestUrl), '/')); 
             }
 
-            $this->targetController = $target[0];
-            $this->targetAction = (isset($target[1])) ? $target[1] : 'index';
-
-            $this->routeMatched = true;
-            $this->matchedRoute = $route;
+            $matched = true;
+        }
 
+        if($matched) {
+            return $params;
         }
 
+        return false;
+
     }
 
     /**
index 4356c34..cc08944 100644 (file)
@@ -3,17 +3,16 @@
 require 'Router.php';
 require 'Route.php';
 
-// construct Router instance, specifying the base request url as a parameter.
-$r = new Router();
+$router = new Router();
 
-$r->setBasePath('/rest-router');
+$router->setBasePath('/rest-router');
 
 // maps / to controller 'users' and method 'index'.
-$r->map('/', 'users#index', array('methods' => 'GET'));
+$router->map('/', 'users#index', array('methods' => 'GET'));
+$router->map('/users/:id/edit/', 'users#edit', array('methods' => 'GET', 'name' => 'user_edit_page'));
 
-$r->map('/users/:id/edit', 'users#edit', array('methods' => 'GET', 'name' => 'user_edit_page'));
-
-$r->execute();
+$params = $router->matchCurrentRequest();
+var_dump($params);
 
 // maps /user/5 to controller 'users', method 'show' with parameter 'id' => 5
 // this route won't match /users/i5 because of the filter regex.
@@ -27,17 +26,6 @@ $r->execute();
 
 // maps GET /users/5/edit to controller 'users', method 'edit' with parameters 'id' => 5 and saves route as a named route.
 
-
-if ($r->isRouteMatched()) {
-    ?>
-    <h1>Route found!</h1>
-    <p><b>Target: </b><?php var_dump($r->targetController); ?></p>
-    <p><b>Params: </b><?php var_dump($r->getArguments()); ?></p>
-    <?php
-} else {
-    ?><h1>No route found.</h1><?php
-}
-
 ?><h3>Reversed routing</h3><?php 
 // echoes /users/5/edit
-echo "Route for user_edit_page with ID 5: ". $r->reverse('user_edit_page', array('id' => '5'));
\ No newline at end of file
+echo "Route for user_edit_page with ID 5: ". $router->reverse('user_edit_page', array('id' => '5'));
\ No newline at end of file