浏览代码

[Routing] added a way to set default parameters that are applied when generating URLs

Fabien Potencier 14 年之前
父节点
当前提交
c6dcf0f8f3

+ 2 - 1
src/Symfony/Component/Routing/Generator/UrlGenerator.php

@@ -79,7 +79,8 @@ class UrlGenerator implements UrlGeneratorInterface
      */
     protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
     {
-        $tparams = array_merge($defaults, $parameters);
+        $parameters = array_replace($this->context->getParameters(), $parameters);
+        $tparams = array_replace($defaults, $parameters);
 
         // all params must be given
         if ($diff = array_diff_key($variables, $tparams)) {

+ 63 - 0
src/Symfony/Component/Routing/RequestContext.php

@@ -24,6 +24,7 @@ class RequestContext
     private $scheme;
     private $httpPort;
     private $httpsPort;
+    private $parameters;
 
     /**
      * Constructor.
@@ -43,6 +44,7 @@ class RequestContext
         $this->scheme = strtolower($scheme);
         $this->httpPort = $httpPort;
         $this->httpsPort = $httpsPort;
+        $this->parameters = array();
     }
 
     /**
@@ -164,4 +166,65 @@ class RequestContext
     {
         $this->httpsPort = $httpsPort;
     }
+
+    /**
+     * Returns the parameters.
+     *
+     * @return array The parameters
+     */
+    public function getParameters()
+    {
+        return $this->parameters;
+    }
+
+    /**
+     * Sets the parameters.
+     *
+     * This method implements a fluent interface.
+     *
+     * @param array $parameters The parameters
+     *
+     * @return Route The current Route instance
+     */
+    public function setParameters(array $parameters)
+    {
+        $this->parameters = $parameters;
+
+        return $this;
+    }
+
+    /**
+     * Gets a parameter value.
+     *
+     * @param string $name A parameter name
+     *
+     * @return mixed The parameter value
+     */
+    public function getParameter($name)
+    {
+        return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
+    }
+
+    /**
+     * Checks if a parameter value is set for the given parameter.
+     *
+     * @param string $name A parameter name
+     *
+     * @return Boolean true if the parameter value is set, false otherwise
+     */
+    public function hasParameter($name)
+    {
+        return array_key_exists($name, $this->parameters);
+    }
+
+    /**
+     * Sets a parameter value.
+     *
+     * @param string $name    A parameter name
+     * @param mixed  $parameter The parameter value
+     */
+    public function setParameter($name, $parameter)
+    {
+        $this->parameters[$name] = $parameter;
+    }
 }