system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CArrayDataProvider

system.web
继承 class CArrayDataProvider » CDataProvider » CComponent
实现 IDataProvider
可用自 1.1.4
源码 framework/web/CArrayDataProvider.php
CArrayDataProvider implements a data provider based on a raw data array.

The rawData property contains all data that may be sorted and/or paginated. CArrayDataProvider will supply the data after sorting and/or pagination. You may configure the sort and pagination properties to customize sorting and pagination behaviors.

Elements in the raw data array may be either objects (e.g. model objects) or associative arrays (e.g. query results of DAO). Make sure to set the keyField property to the name of the field that uniquely identifies a data record or false if you do not have such a field.

CArrayDataProvider may be used in the following way:
$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll();
// or using: $rawData=User::model()->findAll();
$dataProvider=new CArrayDataProvider($rawData, array(
    'id'=>'user',
    'sort'=>array(
        'attributes'=>array(
             'id', 'username', 'email',
        ),
    ),
    'pagination'=>array(
        'pageSize'=>10,
    ),
));
// $dataProvider->getData() will return a list of arrays.


Note: if you want to use the sorting feature, you must configure sort property so that the provider knows which columns can be sorted.

公共属性

隐藏继承的属性

属性类型描述被定义在
caseSensitiveSort boolean controls how sorting works. CArrayDataProvider
data array Returns the data items currently available. CDataProvider
id string Returns the ID that uniquely identifies the data provider. CDataProvider
itemCount integer Returns the number of data items in the current page. CDataProvider
keyField string the name of the key field. CArrayDataProvider
keys array Returns the key values associated with the data items. CDataProvider
pagination CPagination|false Returns the pagination object. CDataProvider
rawData array the data that is not paginated or sorted. CArrayDataProvider
sort CSort|false Returns the sort object. CDataProvider
totalItemCount integer Returns the total number of data items. CDataProvider

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__construct() Constructor. CArrayDataProvider
__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
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
getData() Returns the data items currently available. CDataProvider
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getId() Returns the ID that uniquely identifies the data provider. CDataProvider
getItemCount() Returns the number of data items in the current page. CDataProvider
getKeys() Returns the key values associated with the data items. CDataProvider
getPagination() Returns the pagination object. CDataProvider
getSort() Returns the sort object. CDataProvider
getTotalItemCount() Returns the total number of data items. CDataProvider
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
raiseEvent() Raises an event. CComponent
setData() Sets the data items for this provider. CDataProvider
setId() Sets the provider ID. CDataProvider
setKeys() Sets the data item keys for this provider. CDataProvider
setPagination() Sets the pagination for this data provider. CDataProvider
setSort() Sets the sorting for this data provider. CDataProvider
setTotalItemCount() Sets the total number of data items. CDataProvider

受保护的方法

隐藏继承的方法

方法描述被定义在
calculateTotalItemCount() Calculates the total number of data items. CArrayDataProvider
fetchData() Fetches the data from the persistent data storage. CArrayDataProvider
fetchKeys() Fetches the data item keys from the persistent data storage. CArrayDataProvider
getSortDirections() Converts the "ORDER BY" clause into an array representing the sorting directions. CArrayDataProvider
getSortingFieldValue() Get field for sorting, using dot like delimiter in query. CArrayDataProvider
sortData() Sorts the raw data according to the specified sorting instructions. CArrayDataProvider

属性详情

caseSensitiveSort 属性 (自版本 v1.1.13 可用)
public boolean $caseSensitiveSort;

controls how sorting works. True value means that case will be taken into account. False value will lead to the case insensitive sort. Default value is true.

keyField 属性
public string $keyField;

the name of the key field. This is a field that uniquely identifies a data record. In database this would be the primary key. Defaults to 'id'. If it's set to false, keys of rawData array are used.

rawData 属性
public array $rawData;

the data that is not paginated or sorted. When pagination is enabled, this property usually contains more elements than data. The array elements must use zero-based integer keys.

方法详情

__construct() 方法
public void __construct(array $rawData, array $config=array ( ))
$rawData array the data that is not paginated or sorted. The array elements must use zero-based integer keys.
$config array configuration (name=>value) to be applied as the initial property values of this class.
源码: framework/web/CArrayDataProvider.php#76 (显示)
public function __construct($rawData,$config=array())
{
    
$this->rawData=$rawData;
    foreach(
$config as $key=>$value)
        
$this->$key=$value;
}

Constructor.

calculateTotalItemCount() 方法
protected integer calculateTotalItemCount()
{return} integer the total number of data items.
源码: framework/web/CArrayDataProvider.php#120 (显示)
protected function calculateTotalItemCount()
{
    return 
count($this->rawData);
}

Calculates the total number of data items. This method simply returns the number of elements in rawData.

fetchData() 方法
protected array fetchData()
{return} array list of data items
源码: framework/web/CArrayDataProvider.php#87 (显示)
protected function fetchData()
{
    if((
$sort=$this->getSort())!==false && ($order=$sort->getOrderBy())!='')
        
$this->sortData($this->getSortDirections($order));

    if((
$pagination=$this->getPagination())!==false)
    {
        
$pagination->setItemCount($this->getTotalItemCount());
        return 
array_slice($this->rawData$pagination->getOffset(), $pagination->getLimit());
    }
    else
        return 
$this->rawData;
}

Fetches the data from the persistent data storage.

fetchKeys() 方法
protected array fetchKeys()
{return} array list of data item keys.
源码: framework/web/CArrayDataProvider.php#105 (显示)
protected function fetchKeys()
{
    if(
$this->keyField===false)
        return 
array_keys($this->rawData);
    
$keys=array();
    foreach(
$this->getData() as $i=>$data)
        
$keys[$i]=is_object($data) ? $data->{$this->keyField} : $data[$this->keyField];
    return 
$keys;
}

Fetches the data item keys from the persistent data storage.

getSortDirections() 方法
protected array getSortDirections(string $order)
$order string the "ORDER BY" clause.
{return} array the sorting directions (field name => whether it is descending sort)
源码: framework/web/CArrayDataProvider.php#187 (显示)
protected function getSortDirections($order)
{
    
$segs=explode(',',$order);
    
$directions=array();
    foreach(
$segs as $seg)
    {
        if(
preg_match('/(.*?)(\s+(desc|asc))?$/i',trim($seg),$matches))
            
$directions[$matches[1]]=isset($matches[3]) && !strcasecmp($matches[3],'desc');
        else
            
$directions[trim($seg)]=false;
    }
    return 
$directions;
}

Converts the "ORDER BY" clause into an array representing the sorting directions.

getSortingFieldValue() 方法
protected mixed getSortingFieldValue(mixed $data, array $fields)
$data mixed array or object
$fields array sorting fields in $data
{return} mixed $data sorting field value
源码: framework/web/CArrayDataProvider.php#167 (显示)
protected function getSortingFieldValue($data$fields)
{
    if(
is_object($data))
    {
        foreach(
$fields as $field)
            
$data=isset($data->$field) ? $data->$field null;
    }
    else
    {
        foreach(
$fields as $field)
            
$data=isset($data[$field]) ? $data[$field] : null;
    }
    return 
$this->caseSensitiveSort $data mb_strtolower($data,Yii::app()->charset);
}

Get field for sorting, using dot like delimiter in query.

sortData() 方法
protected void sortData(array $directions)
$directions array the sorting directions (field name => whether it is descending sort)
源码: framework/web/CArrayDataProvider.php#130 (显示)
protected function sortData($directions)
{
    if(empty(
$directions) || empty($this->rawData))
        return;
    
$args=array();
    
$dummy=array();
    foreach(
$directions as $name=>$descending)
    {
        
$column=array();
        
$fields_array=preg_split('/\.+/',$name,-1,PREG_SPLIT_NO_EMPTY);
        foreach(
$this->rawData as $index=>$data)
            
$column[$index]=$this->getSortingFieldValue($data$fields_array);
        
$args[]=&$column;
        
$dummy[]=&$column;
        unset(
$column);
        
$direction=$descending SORT_DESC SORT_ASC;
        
$args[]=&$direction;
        
$dummy[]=&$direction;
        unset(
$direction);
    }

    
// This fix is used for cases when main sorting specified by columns has equal values
    // Without it it will lead to Fatal Error: Nesting level too deep - recursive dependency?
    
$args[]=range(1,count($this->rawData));
    
$args[]=SORT_ASC;
    
$args[]=SORT_NUMERIC;

    
$args[]=&$this->rawData;
    
call_user_func_array('array_multisort'$args);
}

Sorts the raw data according to the specified sorting instructions. After calling this method, rawData will be modified.