Commit eeed9c3f by Qiang Xue

Fixes #998: Added support for generating canonical URL.

parent 1c1cd863
...@@ -24,6 +24,10 @@ class Controller extends \yii\base\Controller ...@@ -24,6 +24,10 @@ class Controller extends \yii\base\Controller
* CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true. * CSRF validation is enabled only when both this property and [[Request::enableCsrfValidation]] are true.
*/ */
public $enableCsrfValidation = true; public $enableCsrfValidation = true;
/**
* @var array the parameters bound to the current action. This is mainly used by [[getCanonicalUrl()]].
*/
public $actionParams = [];
/** /**
* Binds the parameters to the action. * Binds the parameters to the action.
...@@ -46,13 +50,14 @@ class Controller extends \yii\base\Controller ...@@ -46,13 +50,14 @@ class Controller extends \yii\base\Controller
$args = []; $args = [];
$missing = []; $missing = [];
$actionParams = [];
foreach ($method->getParameters() as $param) { foreach ($method->getParameters() as $param) {
$name = $param->getName(); $name = $param->getName();
if (array_key_exists($name, $params)) { if (array_key_exists($name, $params)) {
$args[] = $params[$name]; $args[] = $actionParams[$name] = $params[$name];
unset($params[$name]); unset($params[$name]);
} elseif ($param->isDefaultValueAvailable()) { } elseif ($param->isDefaultValueAvailable()) {
$args[] = $param->getDefaultValue(); $args[] = $actionParams[$name] = $param->getDefaultValue();
} else { } else {
$missing[] = $name; $missing[] = $name;
} }
...@@ -63,6 +68,8 @@ class Controller extends \yii\base\Controller ...@@ -63,6 +68,8 @@ class Controller extends \yii\base\Controller
'params' => implode(', ', $missing), 'params' => implode(', ', $missing),
])); ]));
} }
$this->actionParams = $actionParams;
return $args; return $args;
} }
...@@ -113,6 +120,22 @@ class Controller extends \yii\base\Controller ...@@ -113,6 +120,22 @@ class Controller extends \yii\base\Controller
} }
/** /**
* Returns the canonical URL of the currently requested page.
* The canonical URL is constructed using [[route]] and [[actionParams]]. You may use the following code
* in the layout view to add a link tag about canonical URL:
*
* ~~~
* $this->registerLinkTag(['rel' => 'canonical', 'href' => Yii::$app->controller->canonicalUrl]);
* ~~~
*
* @return string
*/
public function getCanonicalUrl()
{
return Yii::$app->getUrlManager()->createAbsoluteUrl($this->getRoute(), $this->actionParams);
}
/**
* Redirects the browser to the specified URL. * Redirects the browser to the specified URL.
* This method is a shortcut to [[Response::redirect()]]. * This method is a shortcut to [[Response::redirect()]].
* *
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment