Package | system.web |
---|---|
Inheritance | class CUrlManager » CApplicationComponent » CComponent |
Implements | IApplicationComponent |
Since | 1.0 |
Source Code | framework/web/CUrlManager.php |
array( 'articles'=>'article/list', 'article/<id:\d+>/*'=>'article/read', )Two rules are specified in the above:
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 '<_c>' and '<_a>' in the route part. The '<_c>' parameter matches either 'post' or 'comment', while the '<_a>' parameter matches an action ID.
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.
array( 'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile', )
array( // a standard rule '<action:(login|logout)>' => 'site/<action>', // a custom rule using data in DB array( 'class' => 'application.components.MyUrlRule', 'connectionID' => 'db', ), )Please note that the custom URL rule class should extend from CBaseUrlRule and implement the following two methods,
Property | Type | Description | Defined By |
---|---|---|---|
appendParams | boolean | whether to append GET parameters to the path info part. | CUrlManager |
baseUrl | string | Returns the base URL of the application. | CUrlManager |
behaviors | array | the behaviors that should be attached to this component. | CApplicationComponent |
cacheID | string | the ID of the cache application component that is used to cache the parsed URL rules. | CUrlManager |
caseSensitive | boolean | whether routes are case-sensitive. | CUrlManager |
isInitialized | boolean | Checks if this application component has been initialized. | CApplicationComponent |
matchValue | boolean | whether the GET parameter values should match the corresponding sub-patterns in a rule before using it to create a URL. | CUrlManager |
routeVar | string | the GET variable name for route. | CUrlManager |
rules | array | the URL rules (pattern=>route). | CUrlManager |
showScriptName | boolean | whether to show entry script name in the constructed URL. | CUrlManager |
urlFormat | string | Returns the URL format. | CUrlManager |
urlRuleClass | string | the class name or path alias for the URL rule instances. | CUrlManager |
urlSuffix | string | the URL suffix used when in 'path' format. | CUrlManager |
useStrictParsing | boolean | whether to enable strict URL parsing. | CUrlManager |
Method | Description | Defined By |
---|---|---|
__call() | Calls the named method which is not a class method. | CComponent |
__get() | Returns a property value, an event handler list or a behavior based on its name. | CComponent |
__isset() | Checks if a property value is null. | CComponent |
__set() | Sets value of a component property. | CComponent |
__unset() | Sets a component property to be null. | CComponent |
addRules() | Adds new URL rules. | CUrlManager |
asa() | Returns the named behavior object. | CComponent |
attachBehavior() | Attaches a behavior to this component. | CComponent |
attachBehaviors() | Attaches a list of behaviors to the component. | CComponent |
attachEventHandler() | Attaches an event handler to an event. | CComponent |
canGetProperty() | Determines whether a property can be read. | CComponent |
canSetProperty() | Determines whether a property can be set. | CComponent |
createPathInfo() | Creates a path info based on the given parameters. | CUrlManager |
createUrl() | Constructs a URL. | CUrlManager |
detachBehavior() | Detaches a behavior from the component. | CComponent |
detachBehaviors() | Detaches all behaviors from the component. | CComponent |
detachEventHandler() | Detaches an existing event handler. | CComponent |
disableBehavior() | Disables an attached behavior. | CComponent |
disableBehaviors() | Disables all behaviors attached to this component. | CComponent |
enableBehavior() | Enables an attached behavior. | CComponent |
enableBehaviors() | Enables all behaviors attached to this component. | CComponent |
evaluateExpression() | Evaluates a PHP expression or callback under the context of this component. | CComponent |
getBaseUrl() | Returns the base URL of the application. | CUrlManager |
getEventHandlers() | Returns the list of attached event handlers for an event. | CComponent |
getIsInitialized() | Checks if this application component has been initialized. | CApplicationComponent |
getUrlFormat() | Returns the URL format. | CUrlManager |
hasEvent() | Determines whether an event is defined. | CComponent |
hasEventHandler() | Checks whether the named event has attached handlers. | CComponent |
hasProperty() | Determines whether a property is defined. | 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() | Raises an event. | 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 |
Method | Description | Defined By |
---|---|---|
createUrlDefault() | Creates a URL based on default settings. | CUrlManager |
createUrlRule() | Creates a URL rule instance. | CUrlManager |
processRules() | Processes the URL rules. | CUrlManager |
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.
Returns the base URL of the application.
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.
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.
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.
the GET variable name for route. Defaults to 'r'.
the URL rules (pattern=>route).
whether to show entry script name in the constructed URL. Defaults to true.
Returns the URL format.
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.
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.
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.
public void addRules(array $rules, boolean $append=true)
| ||
$rules | array | new URL rules (pattern=>route). |
$append | boolean | whether the new URL rules should be appended to the existing ones. If false, they will be inserted at the beginning. |
public function addRules($rules,$append=true)
{
if ($append)
{
foreach($rules as $pattern=>$route)
$this->_rules[]=$this->createUrlRule($route,$pattern);
}
else
{
$rules=array_reverse($rules);
foreach($rules as $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.
public string createPathInfo(array $params, string $equal, string $ampersand, string $key=NULL)
| ||
$params | array | list of GET parameters |
$equal | string | the separator between name and value |
$ampersand | string | the separator between name-value pairs |
$key | string | this is used internally. |
{return} | string | the created path info |
public function createPathInfo($params,$equal,$ampersand, $key=null)
{
$pairs = array();
foreach($params as $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((string)$v);
}
return implode($ampersand,$pairs);
}
Creates a path info based on the given parameters.
public string createUrl(string $route, array $params=array (
), string $ampersand='&')
| ||
$route | string | the controller and the action (e.g. article/read) |
$params | array | list 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. |
$ampersand | string | the token separating name-value pairs in the URL. Defaults to '&'. |
{return} | string | the constructed URL |
public function createUrl($route,$params=array(),$ampersand='&')
{
unset($params[$this->routeVar]);
foreach($params as $i=>$param)
if($param===null)
$params[$i]='';
if(isset($params['#']))
{
$anchor='#'.$params['#'];
unset($params['#']);
}
else
$anchor='';
$route=trim($route,'/');
foreach($this->_rules as $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.
protected string createUrlDefault(string $route, array $params, string $ampersand)
| ||
$route | string | the controller and the action (e.g. article/read) |
$params | array | list of GET parameters |
$ampersand | string | the token separating name-value pairs in the URL. |
{return} | string | the constructed URL |
protected function createUrlDefault($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.
protected CUrlRule createUrlRule(mixed $route, string $pattern)
| ||
$route | mixed | the route part of the rule. This could be a string or an array |
$pattern | string | the pattern part of the rule |
{return} | CUrlRule | the URL rule instance |
protected function createUrlRule($route,$pattern)
{
if(is_array($route) && isset($route['class']))
return $route;
else
{
$urlRuleClass=Yii::import($this->urlRuleClass,true);
return new $urlRuleClass($route,$pattern);
}
}
Creates a URL rule instance. The default implementation returns a CUrlRule object.
public string getBaseUrl()
| ||
{return} | string | the 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. |
public function getBaseUrl()
{
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.
public string getUrlFormat()
| ||
{return} | string | the 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. |
public function getUrlFormat()
{
return $this->_urlFormat;
}
Returns the URL format.
public void init()
|
public function init()
{
parent::init();
$this->processRules();
}
Initializes the application component.
public void parsePathInfo(string $pathInfo)
| ||
$pathInfo | string | path info |
public function parsePathInfo($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.
public string parseUrl(CHttpRequest $request)
| ||
$request | CHttpRequest | the request application component |
{return} | string | the route (controllerID/actionID) and perhaps GET parameters in path format. |
public function parseUrl($request)
{
if($this->getUrlFormat()===self::PATH_FORMAT)
{
$rawPathInfo=$request->getPathInfo();
$pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
foreach($this->_rules as $i=>$rule)
{
if(is_array($rule))
$this->_rules[$i]=$rule=Yii::createComponent($rule);
if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
}
if($this->useStrictParsing)
throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{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.
protected void processRules()
|
protected function processRules()
{
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->rules as $pattern=>$route)
$this->_rules[]=$this->createUrlRule($route,$pattern);
if(isset($cache))
$cache->set(self::CACHE_KEY,array($this->_rules,$hash));
}
Processes the URL rules.
public string removeUrlSuffix(string $pathInfo, string $urlSuffix)
| ||
$pathInfo | string | path info part in the URL |
$urlSuffix | string | the URL suffix to be removed |
{return} | string | path info with URL suffix removed. |
public function removeUrlSuffix($pathInfo,$urlSuffix)
{
if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
return substr($pathInfo,0,-strlen($urlSuffix));
else
return $pathInfo;
}
Removes the URL suffix from path info.
public void setBaseUrl(string $value)
| ||
$value | string | the base URL of the application |
public function setBaseUrl($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.
public void setUrlFormat(string $value)
| ||
$value | string | the URL format. It must be either 'path' or 'get'. |
public function setUrlFormat($value)
{
if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
$this->_urlFormat=$value;
else
throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
}
Sets the URL format.
Signup or Login in order to comment.