Можно указать что бы реагировать на любое значение:
'site/test/*'=>'site/test'
Update
Действительно в yii2 знак * экранируется, в отличии от yii1.x .
Простого способа не нашел (ранее с подобной задачей не сталкивался), возможно кто то подскажет как сделать иначе.
Вижу два варианта.
Первый самый простой:
//действие
public function actionIndex(){
var_dump($_GET);
}
//правило
'site/test'=>'web/default/index'
Тут все просто, убираем из действия все параметры, и просто смотрим в переменной $_GET. Но остается проблема с созданием урл.
Тут так же два варианта:
Переопределить метод UrlManager::createUrl()
, примерно:
namespace app\components;
class UrlManager extends \yii\web\UrlManager
{
public function createUrl($params, $showParams=true)
{
$url = parent::createUrl($params);
if($showParams){
$url = str_replace(['?', '=', '&'], '/', $url);
}else{
$data = explode('?', $url);
if(isset($data[1])){
preg_match_all('/\=(.*?)(?:&|$)/', $data[1], $matches);
$url = $data[0].'/'.implode('/', $matches[1]);
}
}
return $url;
}
}
в конфиге:
'components' => [
'urlManager' => [
'class'=>'app\components\UrlManager',
...
получаем урл:
\yii\helpers\Url::to(['web/default/index', 'a'=>1, 'b'=>2], true);
или
Yii::$app->urlManager->createUrl(['composerGui/default/test-test', 'a'=>1])
Во втором случае можно скрыть название параметров, передав второй параметр false
Так же можно переопределить метод Url::to()
, примерно:
namespace app\components;
use yii\helpers\BaseUrl;
class Url extends BaseUrl
{
public static function to($url = '', $scheme = false, $showParams=true){
$url = parent::to($url, $scheme);
if($showParams){
$url = str_replace(['?', '=', '&'], '/', $url);
}else{
$data = explode('?', $url);
if(isset($data[1])){
preg_match_all('/\=(.*?)(?:&|$)/', $data[1], $matches);
$url = $data[0].'/'.implode('/', $matches[1]);
}
}
return $url;
}
}
Использовать:
\app\components\Url::to(['site/test', 'a'=>1, 'b'=>2], true);
или что бы скрыть название параметров:
\app\components\Url::to(['site/test', 'a'=>1, 'b'=>2], true, false);
Ну тут выбирать уже что лучше только вам.
Второй вариант для написания правил, это написать свой класс для правил, примерно:
namespace app\components;
use yii\web\Request;
use yii\web\UrlManager;
use yii\web\UrlRule;
/**
* AnyParamsRule represents a rule used by [[UrlManager]] for parsing and generating URLs with an unknown number of parameters.
*
* ```php
* 'rules' => [
* [
* 'class' => 'app\components\AnyParamsRule',
* 'pattern' => 'tyt/test', //wat url do you want see
* 'route' => 'site/index', //what action will be executed
* 'showParams'=>true, //need show parameters on the url or not /site/index/param1/val1/param2/val2 or /site/index/val1/val2
* 'defaults'=>['a'=>null, 'b'=>null, 'c'=>null] //if showParams is false need write all parameters what will be
* ],
* // ...
* ]
* ```
*
* @author Bookin <[email protected]>
*/
class AnyParamsRule extends UrlRule
{
public $showParams = false;
/**
* Creates a URL according to the given route and parameters.
* @param UrlManager $manager the URL manager
* @param string $route the route. It should not have slashes at the beginning or the end.
* @param array $params the parameters
* @return string|boolean the created URL, or `false` if this rule cannot be used for creating this URL.
*/
public function createUrl($manager, $route, $params){
$url = false;
$sep = '/';
if($this->route == $route){
$url = $this->name;
if($this->showParams === true){
foreach( $params as $key => $value ) {
$url .= $sep . $key . ':' . $value;
}
}else{
$url.=$sep.implode($sep, $params);
}
}
return $url;
}
/**
* Parses the given request and returns the corresponding route and parameters.
* @param UrlManager $manager the URL manager
* @param Request $request the request component
* @return array|boolean the parsing result. The route and the parameters are returned as an array.
* If `false`, it means this rule cannot be used to parse this path info.
*/
public function parseRequest($manager, $request){
$pathInfo = $request->getPathInfo();
$attributes = [];
if(stristr($pathInfo, $this->name) === false){
return false;
}
$params = str_replace($this->name, '', $pathInfo);
$params = ltrim($params, '/');
if($params){
$params = array_filter(explode('/', $params));
$params_length = count($params);
if($this->showParams === true){
foreach ($params as $i=>$param){
if(($i+1)%2 == 0){
$attributes[$params[$i-1]]=$param;
}else{
$attributes[$params[$i]]='';
}
}
}else if(is_array($this->defaults) && $params_length <= ($defaults_length = count($this->defaults))){
$fake = array_fill($params_length,$defaults_length-$params_length, null);
$attributes = array_combine(array_keys($this->defaults), $params+$fake);
}else{
$attributes = false;
}
}
foreach ($this->defaults as $name => $value) {
if (!isset($attributes[$name]) || ($attributes[$name] === null && $value != null)) {
$attributes[$name] = $value;
}
}
if($attributes === false){
return false;
}else{
return ['composerGui/default/test-test', $attributes];
}
}
}
Использование:
Для url вида - site/test/a/1
или site/test/a/1/b/2
или site/test/a/1/b/2/c/3
'rules' => [
...
[
'class' => 'app\components\AnyParamsRule',
'pattern' => 'site/test',
'route'=>'web/default/index'
],
...
Для url вида - site/test/1
или site/test/1/2
или site/test/1/2/3
'rules' => [
...
[
'class' => 'app\components\AnyParamsRule',
'pattern' => 'site/test',
'route'=>'web/default/index',
'showParams'=>false,
'defaults'=>['a'=>null, 'b'=>null, 'c'=>null] //можно указать параметры по умолчанию
],
Для генерирования урлов используем стандартный компонент:
\yii\helpers\Url::to(['web/default/index', 'a'=>1], true)
P.S. Код не является истиной, и может упускать какие либо моменты или иметь ошибки, буду благодарен за отзывы в gist что бы исправить ошибки и недочеты