0 follower

CUrlManager

Package system.web
Inheritance class CUrlManager » CApplicationComponent » CComponent
Implements IApplicationComponent
Since 1.0
Version $Id$
Source Code 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/&lt;id:\d+&gt;/*'=>'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 applies when constructing such a URL.
  • The second rule contains a named parameter 'id' which is specified using the <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.


Starting from version 1.0.5, 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(
     '&lt;_c:(post|comment)&gt;/&lt;id:\d+&gt;/&lt;_a:(create|update|delete)&gt;'=>'&lt;_c&gt;/&lt;_a&gt;',
     '&lt;_c:(post|comment)&gt;/&lt;id:\d+&gt;'=>'&lt;_a&gt;/view',
     '&lt;_c:(post|comment)&gt;s/*'=>'&lt;_a>/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.

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'.

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

Public Properties

Hide inherited properties

PropertyTypeDescriptionDefined By
appendParams boolean whether to append GET parameters to the path info part. CUrlManager
baseUrl string the base URL of the application (the part after host name and before query string). 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 whether this application component has been initialized (i.e., init() is invoked. CApplicationComponent
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 the URL format. CUrlManager
urlSuffix string the URL suffix used when in 'path' format. CUrlManager
useStrictParsing boolean whether to enable strict URL parsing. CUrlManager

Public Methods

Hide inherited methods

MethodDescriptionDefined 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
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
getBaseUrl() Returns 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. CUrlManager
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getIsInitialized() Checks whether this application component has been initialized (i.e., init() is invoked.) CApplicationComponent
getUrlFormat() Returns 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. 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
setUrlFormat() Sets the URL format. It must be either 'path' or 'get'. CUrlManager

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
createUrlDefault() Contructs a URL based on default settings. CUrlManager
processRules() Processes the URL rules. CUrlManager

Property Details

appendParams property (available since v1.0.3)
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 property read-only
public string getBaseUrl()

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.

cacheID property (available since v1.0.3)
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 property (available since v1.0.1)
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.

routeVar property
public string $routeVar;

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

rules property
public array $rules;

the URL rules (pattern=>route).

showScriptName property
public boolean $showScriptName;

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

urlFormat property
public string getUrlFormat()
public void setUrlFormat(string $value)

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.

urlSuffix property
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 property (available since v1.0.6)
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.

Method Details

createPathInfo() method (available since v1.0.3)
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
Source Code: framework/web/CUrlManager.php#324 (show)
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($v);
    }
    return 
implode($ampersand,$pairs);
}

Creates a path info based on the given parameters.

createUrl() method
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. This anchor feature has been available since version 1.0.1.
$ampersand string the token separating name-value pairs in the URL. Defaults to '&'.
{return} string the constructed URL
Source Code: framework/web/CUrlManager.php#189 (show)
public function createUrl($route,$params=array(),$ampersand='&')
{
    unset(
$params[$this->routeVar]);
    foreach(
$params as &$param)
        if(
$param===null)
            
$param='';
    if(isset(
$params['#']))
    {
        
$anchor='#'.$params['#'];
        unset(
$params['#']);
    }
    else
        
$anchor='';
    
$route=trim($route,'/');
    foreach(
$this->_rules as $rule)
    {
        if((
$url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
            return 
$rule->hasHostInfo $url.$anchor $this->getBaseUrl().'/'.$url.$anchor;
    }
    return 
$this->createUrlDefault($route,$params,$ampersand).$anchor;
}

Constructs a URL.

createUrlDefault() method
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
Source Code: framework/web/CUrlManager.php#218 (show)
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;
        }
        else if((
$query=$this->createPathInfo($params,'=',$ampersand))!=='')
            
$url.='?'.$query;
        return 
$url;
    }
}

Contructs a URL based on default settings.

getBaseUrl() method
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.
Source Code: framework/web/CUrlManager.php#359 (show)
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;
    }
}

getUrlFormat() method
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.
Source Code: framework/web/CUrlManager.php#377 (show)
public function getUrlFormat()
{
    return 
$this->_urlFormat;
}

init() method
public void init()
Source Code: framework/web/CUrlManager.php#152 (show)
public function init()
{
    
parent::init();
    
$this->processRules();
}

Initializes the application component.

parsePathInfo() method (available since v1.0.3)
public static void parsePathInfo(string $pathInfo)
$pathInfo string path info
Source Code: framework/web/CUrlManager.php#288 (show)
public static 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 && ($pos2=strpos($key,']',$pos+1))!==false)
        {
            
$name=substr($key,0,$pos);
            if(
$pos2===$pos+1)
                
$_REQUEST[$name][]=$_GET[$name][]=$value;
            else
            {
                
$key=substr($key,$pos+1,$pos2-$pos-1);
                
$_REQUEST[$name][$key]=$_GET[$name][$key]=$value;
            }
        }
        else
            
$_REQUEST[$key]=$_GET[$key]=$value;
    }
}

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

parseUrl() method
public string parseUrl(CHttpRequest $request)
$request CHttpRequest the request application component
{return} string the route (controllerID/actionID) and perhaps GET parameters in path format.
Source Code: framework/web/CUrlManager.php#258 (show)
public function parseUrl($request)
{
    if(
$this->getUrlFormat()===self::PATH_FORMAT)
    {
        
$rawPathInfo=urldecode($request->getPathInfo());
        
$pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
        foreach(
$this->_rules as $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;
    }
    else if(isset(
$_GET[$this->routeVar]))
        return 
$_GET[$this->routeVar];
    else if(isset(
$_POST[$this->routeVar]))
        return 
$_POST[$this->routeVar];
    else
        return 
'';
}

Parses the user request.

processRules() method
protected void processRules()
Source Code: framework/web/CUrlManager.php#161 (show)
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[]=new CUrlRule($route,$pattern);
    if(isset(
$cache))
        
$cache->set(self::CACHE_KEY,array($this->_rules,$hash));
}

Processes the URL rules.

removeUrlSuffix() method
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.
Source Code: framework/web/CUrlManager.php#346 (show)
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.

setUrlFormat() method
public void setUrlFormat(string $value)
$value string the URL format. It must be either 'path' or 'get'.
Source Code: framework/web/CUrlManager.php#385 (show)
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".'));
}