Php 重写路径取决于参数值Yii
我在Yii中有几个规则,允许我重写一些路由,其中每个路由都将作为get参数传递给操作Php 重写路径取决于参数值Yii,php,yii,url-rewriting,Php,Yii,Url Rewriting,我在Yii中有几个规则,允许我重写一些路由,其中每个路由都将作为get参数传递给操作 '<department>' => 'products/index', '<department>/<category>' => 'products/index', “”=>“产品/索引”, “/”=>“产品/索引”, 我想显式地编写一个规则,根据参数值的不同,将url更改为我想要的任何内容 例如,现在我有一个这样的URL www.mysite.com/Boo
'<department>' => 'products/index',
'<department>/<category>' => 'products/index',
“”=>“产品/索引”,
“/”=>“产品/索引”,
我想显式地编写一个规则,根据参数值的不同,将url更改为我想要的任何内容
例如,现在我有一个这样的URL
www.mysite.com/Books+%26+铅笔,由于此规则被重写'=>“产品/索引”
,这是正常的
如果有人知道如何编写一条规则,比较deparment属性的值,然后将其重写为我想要的任何内容,那么我想将该URL更改为www.mysite.com/books-pencils
谢谢首先,如果您想更改URL,您应该执行重定向(在本例中)。要实现此逻辑,可以使用 Url管理器配置:
'rules' => array(
// custom url rule class
array(
'class' => 'application.components.MyUrlRule',
),
)
MyUrlRule类:
class MyUrlRule extends CBaseUrlRule
{
public function createUrl($manager,$route,$params,$ampersand)
{
// Logic used to create url.
// If you do not create urls using Yii::app()->createUrl() in your app,
// you can leave it empty.
}
public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
{
// modify url
$pathInfoCleaned = strtolower(preg_replace('+%26+', '-', $pathInfo));
// redirect if needed
if ($pathInfo !== $pathInfoCleaned) {
$request->redirect($pathInfoCleaned, true, 301);
}
// parse params from url
$params = explode('/', $pathInfo);
if (isset($params[0])) {
$_GET['department'] = $params[0];
if (isset($params[1])) {
$_GET['category'] = $params[1];
}
}
return 'products/index';
}
}
您可以使用自定义类来处理特殊请求。 我使用了类似的方法,从数据库中获取自定义URL:
'urlManager'=>array(
'rules'=>array(
array(
'class' => 'application.components.UrlRule',
),
),
),
然后创建类似以下内容的custo类:
<?php
Yii::import("CBaseRule");
class UrlRule extends CBaseUrlRule
{
public function createUrl($manager,$route,$params,$ampersand)
{
// check for my special case of URL route, if not found, then return the unchaged route
preg_match("/^(.+)\/(.+)$/", $route, $r);
if(!is_array($r) or !isset($r[1]) or !isset($r[2])) {
return $route;
}
// handle your own route request, and create your url
$url = 'my-own-url/some-thing';
// check for any params, which i also want to add
$urlParams = $manager->createPathInfo($params,"=","&");
$return = trim($url,'/');
$return.= $urlParams ? "?" . $urlParams : "";
return $return;
}
public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
{
// handle my special url request
$controller = '....';
$action = '.....';
// return the controller/action that should be used
return lcfirst($controller)."/".$action;
}
}
// check my route and params, and if I need to redirect
$request->redirect('/your/new/url/?params=bla',true,'301');