CUrlManager

优质
小牛编辑
133浏览
2023-12-01
所有包 | 属性 | 方法
system.web
继承class CUrlManager » CApplicationComponent » CComponent
实现IApplicationComponent
源自1.0
版本$Id: CUrlManager.php 3515 2011-12-28 12:29:24Z mdomba $
源码framework/web/CUrlManager.php
CUrlManager manages the URLs of Yii Web applications.

It provides URL construction (createUrl()) as well as parsing (parseUrl()) functionality.

URLs managed via CUrlManager can be in one of the following two formats, by setting urlFormat property:
  • 'path' format: /path/to/EntryScript.php/name1/value1/name2/value2...
  • 'get' format: /path/to/EntryScript.php?name1=value1&name2=value2...


When using 'path' format, CUrlManager uses a set of rules to:
  • parse the requested URL into a route ('ControllerID/ActionID') and GET parameters;
  • create URLs based on the given route and GET parameters.


A rule consists of a route and a pattern. The latter is used by CUrlManager to determine which rule is used for parsing/creating URLs. A pattern is meant to match the path info part of a URL. It may contain named parameters using the syntax '<ParamName:RegExp>'.

When parsing a URL, a matching rule will extract the named parameters from the path info and put them into the $_GET variable; when creating a URL, a matching rule will extract the named parameters from $_GET and put them into the path info part of the created URL.

If a pattern ends with '/*', it means additional GET parameters may be appended to the path info part of the URL; otherwise, the GET parameters can only appear in the query string part.

To specify URL rules, set the rules property as an array of rules (pattern=>route). For example,
array(  'articles'=>'article/list',  'article/<id:d+>/*'=>'article/read',
)
Two rules are specified in the above:
  • The first rule says that if the user requests the URL '/path/to/index.php/articles',it should be treated as '/path/to/index.php/article/list'; and vice versa applieswhen constructing such a URL.
  • The second rule contains a named parameter 'id' which is specified usingthe <ParamName:RegExp> syntax. It says that if the user requests the URL'/path/to/index.php/article/13', it should be treated as '/path/to/index.php/article/read?id=13';and vice versa applies when constructing such a URL.


The route part may contain references to named parameters defined in the pattern part. This allows a rule to be applied to different routes based on matching criteria. For example,
array(   '<_c:(post|comment)>/<id:d+>/<_a:(create|update|delete)>'=>'<_c>/<_a>',   '<_c:(post|comment)>/<id:d+>'=>'<_c>/view',   '<_c:(post|comment)>s/*'=>'<_c>/list',
)
In the above, we use two named parameters '' and '' in the route part. The '' parameter matches either 'post' or 'comment', while the '' parameter matches an action ID.

Like normal rules, these rules can be used for both parsing and creating URLs. For example, using the rules above, the URL '/index.php/post/123/create' would be parsed as the route 'post/create' with GET parameter 'id' being 123. And given the route 'post/list' and GET parameter 'page' being 2, we should get a URL '/index.php/posts/page/2'.

It is also possible to include hostname into the rules for parsing and creating URLs. One may extract part of the hostname to be a GET parameter. For example, the URL http://admin.example.com/en/profile may be parsed into GET parameters user=admin and lang=en. On the other hand, rules with hostname may also be used to create URLs with parameterized hostnames.

In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:
array(  'http://<user:w+>.example.com/<lang:w+>/profile' => 'user/profile',
)


Starting from version 1.1.8, one can write custom URL rule classes and use them for one or several URL rules. For example,
array(// a standard rule'<action:(login|logout)>' => 'site/<action>',// a custom rule using data in DBarray(  'class' => 'application.components.MyUrlRule',  'connectionID' => 'db',),
)
Please note that the custom URL rule class should extend from CBaseUrlRule and implement the following two methods,
  • CBaseUrlRule::createUrl()
  • CBaseUrlRule::parseUrl()


CUrlManager is a default application component that may be accessed via CWebApplication::getUrlManager().

公共属性

隐藏继承属性

属性类型描述定义在
appendParamsbooleanwhether to append GET parameters to the path info part.CUrlManager
baseUrlstringReturns the base URL of the application.CUrlManager
behaviorsarray这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。CApplicationComponent
cacheIDstringthe ID of the cache application component that is used to cache the parsed URL rules.CUrlManager
caseSensitivebooleanwhether routes are case-sensitive.CUrlManager
isInitializedboolean检查应用组件是否已经初始化。CApplicationComponent
matchValuebooleanwhether the GET parameter values should match the corresponding sub-patterns in a rule before using it to create a URL.CUrlManager
routeVarstringthe GET variable name for route.CUrlManager
rulesarraythe URL rules (pattern=>route).CUrlManager
showScriptNamebooleanwhether to show entry script name in the constructed URL.CUrlManager
urlFormatstringReturns the URL format.CUrlManager
urlRuleClassstringthe class name or path alias for the URL rule instances.CUrlManager
urlSuffixstringthe URL suffix used when in 'path' format.CUrlManager
useStrictParsingbooleanwhether to enable strict URL parsing.CUrlManager

公共方法

隐藏继承方法

方法描述定义在
__call()如果类中没有调的方法名,则调用这个方法。CComponent
__get()返回一个属性值、一个事件处理程序列表或一个行为名称。CComponent
__isset()检查一个属性是否为null。CComponent
__set()设置一个组件的属性值。CComponent
__unset()设置一个组件的属性为null。CComponent
addRules()Adds new URL rules.CUrlManager
asa()返回这个名字的行为对象。CComponent
attachBehavior()附加一个行为到组件。CComponent
attachBehaviors()附加一个行为列表到组件。CComponent
attachEventHandler()为事件附加一个事件处理程序。CComponent
canGetProperty()确定属性是否可读。CComponent
canSetProperty()确定属性是否可写。CComponent
createPathInfo()Creates a path info based on the given parameters.CUrlManager
createUrl()Constructs a URL.CUrlManager
detachBehavior()从组件中分离一个行为。CComponent
detachBehaviors()从组件中分离所有行为。CComponent
detachEventHandler()分离一个存在的事件处理程序。CComponent
disableBehavior()禁用一个附加行为。CComponent
disableBehaviors()禁用组件附加的所有行为。CComponent
enableBehavior()启用一个附加行为。CComponent
enableBehaviors()启用组件附加的所有行为。CComponent
evaluateExpression()计算一个PHP表达式,或根据组件上下文执行回调。CComponent
getBaseUrl()Returns the base URL of the application.CUrlManager
getEventHandlers()返回一个事件的附加处理程序列表。CComponent
getIsInitialized()检查应用组件是否已经初始化。CApplicationComponent
getUrlFormat()Returns the URL format.CUrlManager
hasEvent()确定一个事件是否定义。CComponent
hasEventHandler()检查事件是否有附加的处理程序。CComponent
hasProperty()确定属性是否被定义。CComponent
init()Initializes the application component.CUrlManager
parsePathInfo()Parses a path info into URL segments and saves them to $_GET and $_REQUEST.CUrlManager
parseUrl()Parses the user request.CUrlManager
raiseEvent()发起一个事件。CComponent
removeUrlSuffix()Removes the URL suffix from path info.CUrlManager
setBaseUrl()Sets the base URL of the application (the part after host name and before query string).CUrlManager
setUrlFormat()Sets the URL format.CUrlManager

受保护方法

隐藏继承方法

方法描述定义在
createUrlDefault()Creates a URL based on default settings.CUrlManager
createUrlRule()Creates a URL rule instance.CUrlManager
processRules()Processes the URL rules.CUrlManager

属性详细

appendParams 属性 public boolean $appendParams;

whether to append GET parameters to the path info part. Defaults to true. This property is only effective when urlFormat is 'path' and is mainly used when creating URLs. When it is true, GET parameters will be appended to the path info and separate from each other using slashes. If this is false, GET parameters will be in query part.

baseUrl 属性 public string getBaseUrl()
public void setBaseUrl(string $value)

Returns the base URL of the application.

cacheID 属性 public string $cacheID;

the ID of the cache application component that is used to cache the parsed URL rules. Defaults to 'cache' which refers to the primary cache application component. Set this property to false if you want to disable caching URL rules.

caseSensitive 属性 public boolean $caseSensitive;

whether routes are case-sensitive. Defaults to true. By setting this to false, the route in the incoming request will be turned to lower case first before further processing. As a result, you should follow the convention that you use lower case when specifying controller mapping (CWebApplication::controllerMap) and action mapping (CController::actions). Also, the directory names for organizing controllers should be in lower case.

matchValue 属性 (可用自 v1.1.0) public boolean $matchValue;

whether the GET parameter values should match the corresponding sub-patterns in a rule before using it to create a URL. Defaults to false, meaning a rule will be used for creating a URL only if its route and parameter names match the given ones. If this property is set true, then the given parameter values must also match the corresponding parameter sub-patterns. Note that setting this property to true will degrade performance.

routeVar 属性 public string $routeVar;

the GET variable name for route. Defaults to 'r'.

rules 属性 public array $rules;

the URL rules (pattern=>route).

showScriptName 属性 public boolean $showScriptName;

whether to show entry script name in the constructed URL. Defaults to true.

urlFormat 属性 public string getUrlFormat()
public void setUrlFormat(string $value)

Returns the URL format.

urlRuleClass 属性 (可用自 v1.1.8) public string $urlRuleClass;

the class name or path alias for the URL rule instances. Defaults to 'CUrlRule'. If you change this to something else, please make sure that the new class must extend from CBaseUrlRule and have the same constructor signature as CUrlRule. It must also be serializable and autoloadable.

urlSuffix 属性 public string $urlSuffix;

the URL suffix used when in 'path' format. For example, ".html" can be used so that the URL looks like pointing to a static HTML page. Defaults to empty.

useStrictParsing 属性 public boolean $useStrictParsing;

whether to enable strict URL parsing. This property is only effective when urlFormat is 'path'. If it is set true, then an incoming URL must match one of the URL rules. Otherwise, it will be treated as an invalid request and trigger a 404 HTTP exception. Defaults to false.

方法详细

addRules() 方法 (可用自 v1.1.4)
public void addRules(array $rules, boolean $append=true)
$rulesarraynew URL rules (pattern=>route).
$appendbooleanwhether the new URL rules should be appended to the existing ones. If false, they will be inserted at the beginning.
源码: framework/web/CUrlManager.php#241 (显示) publicfunctionaddRules($rules,$append=true)
{
if($append)
{
foreach($rulesas$pattern=>$route)
$this->_rules[]=$this->createUrlRule($route,$pattern);
}
else
{
foreach($rulesas$pattern=>$route)
array_unshift($this->_rules,$this->createUrlRule($route,$pattern));
}
}

Adds new URL rules. In order to make the new rules effective, this method must be called BEFORE CWebApplication::processRequest.

createPathInfo() 方法
public string createPathInfo(array $params, string $equal, string $ampersand, string $key=NULL)
$paramsarraylist of GET parameters
$equalstringthe separator between name and value
$ampersandstringthe separator between name-value pairs
$keystringthis is used internally.
{return}stringthe created path info
源码: framework/web/CUrlManager.php#426 (显示) publicfunctioncreatePathInfo($params,$equal,$ampersand,$key=null)
{
$pairs=array();
foreach($paramsas$k=>$v)
{
if($key!==null)
$k=$key.'['.$k.']';

if(is_array($v))
$pairs[]=$this->createPathInfo($v,$equal,$ampersand,$k);
else
$pairs[]=urlencode($k).$equal.urlencode($v);
}
returnimplode($ampersand,$pairs);
}

Creates a path info based on the given parameters.

createUrl() 方法
public string createUrl(string $route, array $params=array ( ), string $ampersand='&')
$routestringthe controller and the action (e.g. article/read)
$paramsarraylist of GET parameters (name=>value). Both the name and value will be URL-encoded. If the name is '#', the corresponding value will be treated as an anchor and will be appended at the end of the URL.
$ampersandstringthe token separating name-value pairs in the URL. Defaults to '&'.
{return}stringthe constructed URL
源码: framework/web/CUrlManager.php#280 (显示) publicfunctioncreateUrl($route,$params=array(),$ampersand='&')
{
unset($params[$this->routeVar]);
foreach($paramsas$i=>$param)
if($param===null)
$params[$i]='';

if(isset($params['#']))
{
$anchor='#'.$params['#'];
unset($params['#']);
}
else
$anchor='';
$route=trim($route,'/');
foreach($this->_rulesas$i=>$rule)
{
if(is_array($rule))
$this->_rules[$i]=$rule=Yii::createComponent($rule);
if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
{
if($rule->hasHostInfo)
return$url===''?'/'.$anchor:$url.$anchor;
else
return$this->getBaseUrl().'/'.$url.$anchor;
}
}
return$this->createUrlDefault($route,$params,$ampersand).$anchor;
}

Constructs a URL.

createUrlDefault() 方法
protected string createUrlDefault(string $route, array $params, string $ampersand)
$routestringthe controller and the action (e.g. article/read)
$paramsarraylist of GET parameters
$ampersandstringthe token separating name-value pairs in the URL.
{return}stringthe constructed URL
源码: framework/web/CUrlManager.php#317 (显示) protectedfunctioncreateUrlDefault($route,$params,$ampersand)
{
if($this->getUrlFormat()===self::PATH_FORMAT)
{
$url=rtrim($this->getBaseUrl().'/'.$route,'/');
if($this->appendParams)
{
$url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
return$route===''?$url:$url.$this->urlSuffix;
}
else
{
if($route!=='')
$url.=$this->urlSuffix;
$query=$this->createPathInfo($params,'=',$ampersand);
return$query===''?$url:$url.'?'.$query;
}
}
else
{
$url=$this->getBaseUrl();
if(!$this->showScriptName)
$url.='/';
if($route!=='')
{
$url.='?'.$this->routeVar.'='.$route;
if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
$url.=$ampersand.$query;
}
elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
$url.='?'.$query;
return$url;
}
}

Creates a URL based on default settings.

createUrlRule() 方法 (可用自 v1.1.0)
protected CUrlRule createUrlRule(mixed $route, string $pattern)
$routemixedthe route part of the rule. This could be a string or an array
$patternstringthe pattern part of the rule
{return}CUrlRulethe URL rule instance
源码: framework/web/CUrlManager.php#263 (显示) protectedfunctioncreateUrlRule($route,$pattern)
{
if(is_array($route)&&isset($route['class']))
return$route;
else
returnnew$this->urlRuleClass($route,$pattern);
}

Creates a URL rule instance. The default implementation returns a CUrlRule object.

getBaseUrl() 方法
public string getBaseUrl()
{return}stringthe base URL of the application (the part after host name and before query string). If showScriptName is true, it will include the script name part. Otherwise, it will not, and the ending slashes are stripped off.
源码: framework/web/CUrlManager.php#462 (显示) publicfunctiongetBaseUrl()
{
if($this->_baseUrl!==null)
return$this->_baseUrl;
else
{
if($this->showScriptName)
$this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
else
$this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
return$this->_baseUrl;
}
}

Returns the base URL of the application.

getUrlFormat() 方法
public string getUrlFormat()
{return}stringthe URL format. Defaults to 'path'. Valid values include 'path' and 'get'. Please refer to the guide for more details about the difference between these two formats.
源码: framework/web/CUrlManager.php#494 (显示) publicfunctiongetUrlFormat()
{
return$this->_urlFormat;
}

Returns the URL format.

init() 方法
public void init()
源码: framework/web/CUrlManager.php#204 (显示) publicfunctioninit()
{
parent::init();
$this->processRules();
}

Initializes the application component.

parsePathInfo() 方法
public void parsePathInfo(string $pathInfo)
$pathInfostringpath info
源码: framework/web/CUrlManager.php#388 (显示) publicfunctionparsePathInfo($pathInfo)
{
if($pathInfo==='')
return;
$segs=explode('/',$pathInfo.'/');
$n=count($segs);
for($i=0;$i<$n-1;$i+=2)
{
$key=$segs[$i];
if($key==='')continue;
$value=$segs[$i+1];
if(($pos=strpos($key,'['))!==false&&($m=preg_match_all('/[(.*?)]/',$key,$matches))>0)
{
$name=substr($key,0,$pos);
for($j=$m-1;$j>=0;--$j)
{
if($matches[1][$j]==='')
$value=array($value);
else
$value=array($matches[1][$j]=>$value);
}
if(isset($_GET[$name])&&is_array($_GET[$name]))
$value=CMap::mergeArray($_GET[$name],$value);
$_REQUEST[$name]=$_GET[$name]=$value;
}
else
$_REQUEST[$key]=$_GET[$key]=$value;
}
}

Parses a path info into URL segments and saves them to $_GET and $_REQUEST.

parseUrl() 方法
public string parseUrl(CHttpRequest $request)
$requestCHttpRequestthe request application component
{return}stringthe route (controllerID/actionID) and perhaps GET parameters in path format.
源码: framework/web/CUrlManager.php#357 (显示) publicfunctionparseUrl($request)
{
if($this->getUrlFormat()===self::PATH_FORMAT)
{
$rawPathInfo=$request->getPathInfo();
$pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
foreach($this->_rulesas$i=>$rule)
{
if(is_array($rule))
$this->_rules[$i]=$rule=Yii::createComponent($rule);
if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
returnisset($_GET[$this->routeVar])?$_GET[$this->routeVar]:$r;
}
if($this->useStrictParsing)
thrownewCHttpException(404,Yii::t('yii','Unabletoresolvetherequest"{route}".',
array('{route}'=>$pathInfo)));
else
return$pathInfo;
}
elseif(isset($_GET[$this->routeVar]))
return$_GET[$this->routeVar];
elseif(isset($_POST[$this->routeVar]))
return$_POST[$this->routeVar];
else
return'';
}

Parses the user request.

processRules() 方法
protected void processRules()
源码: framework/web/CUrlManager.php#213 (显示) protectedfunctionprocessRules()
{
if(empty($this->rules)||$this->getUrlFormat()===self::GET_FORMAT)
return;
if($this->cacheID!==false&&($cache=Yii::app()->getComponent($this->cacheID))!==null)
{
$hash=md5(serialize($this->rules));
if(($data=$cache->get(self::CACHE_KEY))!==false&&isset($data[1])&&$data[1]===$hash)
{
$this->_rules=$data[0];
return;
}
}
foreach($this->rulesas$pattern=>$route)
$this->_rules[]=$this->createUrlRule($route,$pattern);
if(isset($cache))
$cache->set(self::CACHE_KEY,array($this->_rules,$hash));
}

Processes the URL rules.

removeUrlSuffix() 方法
public string removeUrlSuffix(string $pathInfo, string $urlSuffix)
$pathInfostringpath info part in the URL
$urlSuffixstringthe URL suffix to be removed
{return}stringpath info with URL suffix removed.
源码: framework/web/CUrlManager.php#448 (显示) publicfunctionremoveUrlSuffix($pathInfo,$urlSuffix)
{
if($urlSuffix!==''&&substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
returnsubstr($pathInfo,0,-strlen($urlSuffix));
else
return$pathInfo;
}

Removes the URL suffix from path info.

setBaseUrl() 方法 (可用自 v1.1.1)
public void setBaseUrl(string $value)
$valuestringthe base URL of the application
源码: framework/web/CUrlManager.php#484 (显示) publicfunctionsetBaseUrl($value)
{
$this->_baseUrl=$value;
}

Sets the base URL of the application (the part after host name and before query string). This method is provided in case the baseUrl cannot be determined automatically. The ending slashes should be stripped off. And you are also responsible to remove the script name if you set showScriptName to be false.

setUrlFormat() 方法
public void setUrlFormat(string $value)
$valuestringthe URL format. It must be either 'path' or 'get'.
源码: framework/web/CUrlManager.php#503 (显示) publicfunctionsetUrlFormat($value)
{
if($value===self::PATH_FORMAT||$value===self::GET_FORMAT)
$this->_urlFormat=$value;
else
thrownewCException(Yii::t('yii','CUrlManager.UrlFormatmustbeeither"path"or"get".'));
}

Sets the URL format.