OSDN Git Service

Added parameters by name
authorAntoine pous <Antoine-Pous@users.noreply.github.com>
Tue, 7 Apr 2015 16:23:42 +0000 (18:23 +0200)
committerAntoine pous <Antoine-Pous@users.noreply.github.com>
Tue, 7 Apr 2015 16:23:42 +0000 (18:23 +0200)
Parameters by name add simple way to get named parameters into the controller method.
This optionnal argument, set to false by default, is available from setFilters method and can be used individually for each route.

Route :
```PHP
$route = new Route('/:page_id',     ['_controller' => 'App\Controller\someController::method', 'methods' => 'GET' ]);
$route->setFilters([':page_id' => '([a-zA-Z]+)'], true);
```

Controller :
```PHP
class someController
{
  public function myMethod() {
    var_dump(func_get_args());
    // display : array(1) { [0]=> array(1) { ["page_id"]=> string(5) "mySuperPage" } }
  }
}
```

src/PHPRouter/Route.php

index 32ffa42..8075a1b 100755 (executable)
@@ -27,7 +27,6 @@ class Route
 
     /**
      * Accepted HTTP methods for this route.
-     *
      * @var string[]
      */
     private $methods = array('GET', 'POST', 'PUT', 'DELETE');
@@ -57,6 +56,13 @@ class Route
     private $parameters = array();
 
     /**
+     * Set named parameters to target method
+     * @example [ [0] => [ ["link_id"] => "12312" ] ]
+     * @var bool
+     */
+    private $parametersByName;
+    
+    /**
      * @var array
      */
     private $config;
@@ -120,9 +126,14 @@ class Route
         $this->name = (string)$name;
     }
 
-    public function setFilters(array $filters)
+    public function setFilters(array $filters, $parametersByName = false)
     {
         $this->filters = $filters;
+        
+        if($parametersByName) {
+          $this->parametersByName = true;
+        }
+        
     }
 
     public function getRegex()
@@ -143,7 +154,7 @@ class Route
     {
         return $this->parameters;
     }
-
+    
     public function setParameters(array $parameters)
     {
         $this->parameters = $parameters;
@@ -153,6 +164,11 @@ class Route
     {
         $action = explode('::', $this->config['_controller']);
         $instance = new $action[0];
+        
+        if($this->parametersByName) {
+          $this->parameters = array($this->parameters);
+        }
+        
         call_user_func_array(array($instance, $action[1]), $this->parameters);
     }
 }