CSort

优质
小牛编辑
129浏览
2023-12-01
所有包 | 属性 | 方法
system.web
继承class CSort » CComponent
版本$Id: CSort.php 3554 2012-02-08 16:31:30Z alexander.makarow $
源码framework/web/CSort.php
CSort represents information relevant to sorting.

When data needs to be sorted according to one or several attributes, we can use CSort to represent the sorting information and generate appropriate hyperlinks that can lead to sort actions.

CSort is designed to be used together with CActiveRecord. When creating a CSort instance, you need to specify modelClass. You can use CSort to generate hyperlinks by calling link. You can also use CSort to modify a CDbCriteria instance by calling applyOrder so that it can cause the query results to be sorted according to the specified attributes.

In order to prevent SQL injection attacks, CSort ensures that only valid model attributes can be sorted. This is determined based on modelClass and attributes. When attributes is not set, all attributes belonging to modelClass can be sorted. When attributes is set, only those attributes declared in the property can be sorted.

By configuring attributes, one can perform more complex sorts that may consist of things like compound attributes (e.g. sort based on the combination of first name and last name of users).

The property attributes should be an array of key-value pairs, where the keys represent the attribute names, while the values represent the virtual attribute definitions. For more details, please check the documentation about attributes.

公共属性

隐藏继承属性

属性类型描述定义在
attributesarraylist of attributes that are allowed to be sorted.CSort
defaultOrdermixedthe default order that should be applied to the query criteria when the current request does not specify any sort.CSort
descTagstringthe tag appeared in the GET parameter that indicates the attribute should be sorted in descending order.CSort
directionsarrayReturns the currently requested sort information.CSort
modelClassstringthe name of the model class whose attributes can be sorted.CSort
multiSortbooleanwhether the sorting can be applied to multiple attributes simultaneously.CSort
orderBystringthe order-by columns represented by this sort object.CSort
paramsarraythe additional GET parameters (name=>value) that should be used when generating sort URLs.CSort
routestringthe route (controller ID and action ID) for generating the sorted contents.CSort
separatorsarrayseparators used in the generated URL.CSort
sortVarstringthe name of the GET parameter that specifies which attributes to be sorted in which direction.CSort

公共方法

隐藏继承方法

方法描述定义在
__call()如果类中没有调的方法名,则调用这个方法。CComponent
__construct()Constructor.CSort
__get()返回一个属性值、一个事件处理程序列表或一个行为名称。CComponent
__isset()检查一个属性是否为null。CComponent
__set()设置一个组件的属性值。CComponent
__unset()设置一个组件的属性为null。CComponent
applyOrder()Modifies the query criteria by changing its CDbCriteria::order property.CSort
asa()返回这个名字的行为对象。CComponent
attachBehavior()附加一个行为到组件。CComponent
attachBehaviors()附加一个行为列表到组件。CComponent
attachEventHandler()为事件附加一个事件处理程序。CComponent
canGetProperty()确定属性是否可读。CComponent
canSetProperty()确定属性是否可写。CComponent
createUrl()Creates a URL that can lead to generating sorted data.CSort
detachBehavior()从组件中分离一个行为。CComponent
detachBehaviors()从组件中分离所有行为。CComponent
detachEventHandler()分离一个存在的事件处理程序。CComponent
disableBehavior()禁用一个附加行为。CComponent
disableBehaviors()禁用组件附加的所有行为。CComponent
enableBehavior()启用一个附加行为。CComponent
enableBehaviors()启用组件附加的所有行为。CComponent
evaluateExpression()计算一个PHP表达式,或根据组件上下文执行回调。CComponent
getDirection()Returns the sort direction of the specified attribute in the current request.CSort
getDirections()Returns the currently requested sort information.CSort
getEventHandlers()返回一个事件的附加处理程序列表。CComponent
getOrderBy()返回the order-by columns represented by this sort object. This can be put in the ORDER BY clause of a SQL statement.CSort
hasEvent()确定一个事件是否定义。CComponent
hasEventHandler()检查事件是否有附加的处理程序。CComponent
hasProperty()确定属性是否被定义。CComponent
link()Generates a hyperlink that can be clicked to cause sorting.CSort
raiseEvent()发起一个事件。CComponent
resolveAttribute()Returns the real definition of an attribute given its name.CSort
resolveLabel()Resolves the attribute label for the specified attribute.CSort

受保护方法

隐藏继承方法

方法描述定义在
createLink()Creates a hyperlink based on the given label and URL.CSort

属性详细

attributes 属性 public array $attributes;

list of attributes that are allowed to be sorted. For example, array('user_id','create_time') would specify that only 'user_id' and 'create_time' of the model modelClass can be sorted. By default, this property is an empty array, which means all attributes in modelClass are allowed to be sorted.

This property can also be used to specify complex sorting. To do so, a virtual attribute can be declared in terms of a key-value pair in the array. The key refers to the name of the virtual attribute that may appear in the sort request, while the value specifies the definition of the virtual attribute.

In the simple case, a key-value pair can be like 'user'=>'user_id' where 'user' is the name of the virtual attribute while 'user_id' means the virtual attribute is the 'user_id' attribute in the modelClass.

A more flexible way is to specify the key-value pair as

'user'=>array(  'asc'=>'first_name, last_name',  'desc'=>'first_name DESC, last_name DESC',  'label'=>'Name'
)
where 'user' is the name of the virtual attribute that specifies the full name of user (a compound attribute consisting of first name and last name of user). In this case, we have to use an array to define the virtual attribute with three elements: 'asc', 'desc' and 'label'.

The above approach can also be used to declare virtual attributes that consist of relational attributes. For example,
'price'=>array(  'asc'=>'item.price',  'desc'=>'item.price DESC',  'label'=>'Item Price'
)


Note, the attribute name should not contain '-' or '.' characters because they are used as separators.

Starting from version 1.1.3, an additional option named 'default' can be used in the virtual attribute declaration. This option specifies whether an attribute should be sorted in ascending or descending order upon user clicking the corresponding sort hyperlink if it is not currently sorted. The valid option values include 'asc' (default) and 'desc'. For example,
'price'=>array(  'asc'=>'item.price',  'desc'=>'item.price DESC',  'label'=>'Item Price',  'default'=>'desc',
)


Also starting from version 1.1.3, you can include a star ('*') element in this property so that all model attributes are available for sorting, in addition to those virtual attributes. For example,
'attributes'=>array(  'price'=>array(      'asc'=>'item.price',      'desc'=>'item.price DESC',      'label'=>'Item Price',      'default'=>'desc',  ),  '*',
)
Note that when a name appears as both a model attribute and a virtual attribute, the position of the star element in the array determines which one takes precedence. In particular, if the star element is the first element in the array, the model attribute takes precedence; and if the star element is the last one, the virtual attribute takes precedence.

defaultOrder 属性 public mixed $defaultOrder;

the default order that should be applied to the query criteria when the current request does not specify any sort. For example, 'name, create_time DESC' or 'UPPER(name)'.

Starting from version 1.1.3, you can also specify the default order using an array. The array keys could be attribute names or virtual attribute names as declared in attributes, and the array values indicate whether the sorting of the corresponding attributes should be in descending order. For example,

'defaultOrder'=>array(  'price'=>CSort::SORT_DESC,
)


Please note when using array to specify the default order, the corresponding attributes will be put into directions and thus affect how the sort links are rendered (e.g. an arrow may be displayed next to the currently active sort link).

descTag 属性 public string $descTag;

the tag appeared in the GET parameter that indicates the attribute should be sorted in descending order. Defaults to 'desc'.

directions 属性 只读 public array getDirections()

Returns the currently requested sort information.

modelClass 属性 public string $modelClass;

the name of the model class whose attributes can be sorted. The model class must be a child class of CActiveRecord.

multiSort 属性 public boolean $multiSort;

whether the sorting can be applied to multiple attributes simultaneously. Defaults to false, which means each time the data can only be sorted by one attribute.

orderBy 属性 只读 (可用自 v1.1.0) public string getOrderBy()

the order-by columns represented by this sort object. This can be put in the ORDER BY clause of a SQL statement.

params 属性 public array $params;

the additional GET parameters (name=>value) that should be used when generating sort URLs. Defaults to null, meaning using the currently available GET parameters.

route 属性 public string $route;

the route (controller ID and action ID) for generating the sorted contents. Defaults to empty string, meaning using the currently requested route.

separators 属性 public array $separators;

separators used in the generated URL. This must be an array consisting of two elements. The first element specifies the character separating different attributes, while the second element specifies the character separating attribute name and the corresponding sort direction. Defaults to array('-','.').

sortVar 属性 public string $sortVar;

the name of the GET parameter that specifies which attributes to be sorted in which direction. Defaults to 'sort'.

方法详细

__construct() 方法
public void __construct(string $modelClass=NULL)
$modelClassstringthe class name of data models that need to be sorted. This should be a child class of CActiveRecord.
源码: framework/web/CSort.php#202 (显示) publicfunction__construct($modelClass=null)
{
$this->modelClass=$modelClass;
}

Constructor.

applyOrder() 方法
public void applyOrder(CDbCriteria $criteria)
$criteriaCDbCriteriathe query criteria
源码: framework/web/CSort.php#214 (显示) publicfunctionapplyOrder($criteria)
{
$order=$this->getOrderBy();
if(!empty($order))
{
if(!empty($criteria->order))
$criteria->order.=',';
$criteria->order.=$order;
}
}

Modifies the query criteria by changing its CDbCriteria::order property. This method will use directions to determine which columns need to be sorted. They will be put in the ORDER BY clause. If the criteria already has non-empty CDbCriteria::order value, the new value will be appended to it.

createLink() 方法
protected string createLink(string $attribute, string $label, string $url, array $htmlOptions)
$attributestringthe name of the attribute that this link is for
$labelstringthe label of the hyperlink
$urlstringthe URL
$htmlOptionsarrayadditional HTML options
{return}stringthe generated hyperlink
源码: framework/web/CSort.php#453 (显示) protectedfunctioncreateLink($attribute,$label,$url,$htmlOptions)
{
returnCHtml::link($label,$url,$htmlOptions);
}

Creates a hyperlink based on the given label and URL. You may override this method to customize the link generation.

createUrl() 方法
public string createUrl(CController $controller, array $directions)
$controllerCControllerthe controller that will be used to create the URL.
$directionsarraythe sort directions indexed by attribute names. The sort direction can be either CSort::SORT_ASC for ascending order or CSort::SORT_DESC for descending order.
{return}stringthe URL for sorting
源码: framework/web/CSort.php#393 (显示) publicfunctioncreateUrl($controller,$directions)
{
$sorts=array();
foreach($directionsas$attribute=>$descending)
$sorts[]=$descending?$attribute.$this->separators[1].$this->descTag:$attribute;
$params=$this->params===null?$_GET:$this->params;
$params[$this->sortVar]=implode($this->separators[0],$sorts);
return$controller->createUrl($this->route,$params);
}

Creates a URL that can lead to generating sorted data.

getDirection() 方法
public mixed getDirection(string $attribute)
$attributestringthe attribute name
{return}mixedSort direction of the attribute. Can be either CSort::SORT_ASC for ascending order or CSort::SORT_DESC for descending order. Value is null if the attribute doesn't need to be sorted.
源码: framework/web/CSort.php#379 (显示) publicfunctiongetDirection($attribute)
{
$this->getDirections();
returnisset($this->_directions[$attribute])?$this->_directions[$attribute]:null;
}

Returns the sort direction of the specified attribute in the current request.

getDirections() 方法
public array getDirections()
{return}arraysort directions indexed by attribute names. Sort direction can be either CSort::SORT_ASC for ascending order or CSort::SORT_DESC for descending order.
源码: framework/web/CSort.php#339 (显示) publicfunctiongetDirections()
{
if($this->_directions===null)
{
$this->_directions=array();
if(isset($_GET[$this->sortVar])&&is_string($_GET[$this->sortVar]))
{
$attributes=explode($this->separators[0],$_GET[$this->sortVar]);
foreach($attributesas$attribute)
{
if(($pos=strrpos($attribute,$this->separators[1]))!==false)
{
$descending=substr($attribute,$pos+1)===$this->descTag;
if($descending)
$attribute=substr($attribute,0,$pos);
}
else
$descending=false;

if(($this->resolveAttribute($attribute))!==false)
{
$this->_directions[$attribute]=$descending;
if(!$this->multiSort)
return$this->_directions;
}
}
}
if($this->_directions===array()&&is_array($this->defaultOrder))
$this->_directions=$this->defaultOrder;
}
return$this->_directions;
}

Returns the currently requested sort information.

getOrderBy() 方法 (可用自 v1.1.0)
public string getOrderBy()
{return}stringthe order-by columns represented by this sort object. This can be put in the ORDER BY clause of a SQL statement.
源码: framework/web/CSort.php#230 (显示) publicfunctiongetOrderBy()
{
$directions=$this->getDirections();
if(empty($directions))
returnis_string($this->defaultOrder)?$this->defaultOrder:'';
else
{
if($this->modelClass!==null)
$schema=CActiveRecord::model($this->modelClass)->getDbConnection()->getSchema();
$orders=array();
foreach($directionsas$attribute=>$descending)
{
$definition=$this->resolveAttribute($attribute);
if(is_array($definition))
{
if($descending)
$orders[]=isset($definition['desc'])?$definition['desc']:$attribute.'DESC';
else
$orders[]=isset($definition['asc'])?$definition['asc']:$attribute;
}
elseif($definition!==false)
{
$attribute=$definition;
if(isset($schema))
{
if(($pos=strpos($attribute,'.'))!==false)
$attribute=$schema->quoteTableName(substr($attribute,0,$pos)).'.'.$schema->quoteColumnName(substr($attribute,$pos+1));
else
$attribute=CActiveRecord::model($this->modelClass)->getTableAlias(true).'.'.$schema->quoteColumnName($attribute);
}
$orders[]=$descending?$attribute.'DESC':$attribute;
}
}
returnimplode(',',$orders);
}
}
link() 方法
public string link(string $attribute, string $label=NULL, array $htmlOptions=array ( ))
$attributestringthe attribute name. This must be the actual attribute name, not alias. If it is an attribute of a related AR object, the name should be prefixed with the relation name (e.g. 'author.name', where 'author' is the relation name).
$labelstringthe link label. If null, the label will be determined according to the attribute (see resolveLabel).
$htmlOptionsarrayadditional HTML attributes for the hyperlink tag
{return}stringthe generated hyperlink
源码: framework/web/CSort.php#277 (显示) publicfunctionlink($attribute,$label=null,$htmlOptions=array())
{
if($label===null)
$label=$this->resolveLabel($attribute);
if(($definition=$this->resolveAttribute($attribute))===false)
return$label;
$directions=$this->getDirections();
if(isset($directions[$attribute]))
{
$class=$directions[$attribute]?'desc':'asc';
if(isset($htmlOptions['class']))
$htmlOptions['class'].=''.$class;
else
$htmlOptions['class']=$class;
$descending=!$directions[$attribute];
unset($directions[$attribute]);
}
elseif(is_array($definition)&&isset($definition['default']))
$descending=$definition['default']==='desc';
else
$descending=false;

if($this->multiSort)
$directions=array_merge(array($attribute=>$descending),$directions);
else
$directions=array($attribute=>$descending);

$url=$this->createUrl(Yii::app()->getController(),$directions);

return$this->createLink($attribute,$label,$url,$htmlOptions);
}

Generates a hyperlink that can be clicked to cause sorting.

resolveAttribute() 方法
public mixed resolveAttribute(string $attribute)
$attributestringthe attribute name that the user requests to sort on
{return}mixedthe attribute name or the virtual attribute definition. False if the attribute cannot be sorted.
源码: framework/web/CSort.php#418 (显示) publicfunctionresolveAttribute($attribute)
{
if($this->attributes!==array())
$attributes=$this->attributes;
elseif($this->modelClass!==null)
$attributes=CActiveRecord::model($this->modelClass)->attributeNames();
else
returnfalse;
foreach($attributesas$name=>$definition)
{
if(is_string($name))
{
if($name===$attribute)
return$definition;
}
elseif($definition==='*')
{
if($this->modelClass!==null&&CActiveRecord::model($this->modelClass)->hasAttribute($attribute))
return$attribute;
}
elseif($definition===$attribute)
return$attribute;
}
returnfalse;
}

Returns the real definition of an attribute given its name.

The resolution is based on attributes and CActiveRecord::attributeNames.

  • When attributes is an empty array, if the name refers to an attribute of modelClass, then the name is returned back.
  • When attributes is not empty, if the name refers to an attribute declared in attributes, then the corresponding virtual attribute definition is returned. Starting from version 1.1.3, if attributes contains a star ('*') element, the name will also be used to match against all model attributes.
  • In all other cases, false is returned, meaning the name does not refer to a valid attribute.

resolveLabel() 方法
public string resolveLabel(string $attribute)
$attributestringthe attribute name.
{return}stringthe attribute label
源码: framework/web/CSort.php#317 (显示) publicfunctionresolveLabel($attribute)
{
$definition=$this->resolveAttribute($attribute);
if(is_array($definition))
{
if(isset($definition['label']))
return$definition['label'];
}
elseif(is_string($definition))
$attribute=$definition;
if($this->modelClass!==null)
returnCActiveRecord::model($this->modelClass)->getAttributeLabel($attribute);
else
return$attribute;
}

Resolves the attribute label for the specified attribute. This will invoke CActiveRecord::getAttributeLabel to determine what label to use. If the attribute refers to a virtual attribute declared in attributes, then the label given in the attributes will be returned instead.