加载中...

YII框架分析笔记8:CDataProvider


CDataProvider,顾名思义,数据提供者,它提供了三个抽象方法(fetchData,、fetchKeys 和 calculateTotalItemCount),分别为调用不同数据结构的数据提供了获取数据、获取键值、获取数量的,接口,在YII框架中,CActiveDataProvider、CArrayDataProvider、CSqlDataProvider是它的子类,除了提供数据之外,他还提供分页和排序功能。下面以获取数据fetchData()为例

CActiveDataProvider通过CActiveRecord的子类和CDbCriteria对象

/**
    * Fetches the data from the persistent data storage.
    * @return array list of data items
    */
protected function fetchData()
{
    $criteria=clone $this->getCriteria();

    if(($pagination=$this->getPagination())!==false)
    {
        $pagination->setItemCount($this->getTotalItemCount());
        $pagination->applyLimit($criteria);
    }

    $baseCriteria=$this->model->getDbCriteria(false);

    if(($sort=$this->getSort())!==false)
    {
        // set model criteria so that CSort can use its table alias setting
        if($baseCriteria!==null)
        {
            $c=clone $baseCriteria;
            $c->mergeWith($criteria);
            $this->model->setDbCriteria($c);
        }
        else
            $this->model->setDbCriteria($criteria);
        $sort->applyOrder($criteria);
    }

    $this->model->setDbCriteria($baseCriteria!==null ? clone $baseCriteria : null);
    $data=$this->model->findAll($criteria);

    $this->model->setDbCriteria($baseCriteria);  // restore original criteria
    return $data;
}
CArrayDataProvider通过传人的原生数据来获取数据
/**
    * Fetches the data from the persistent data storage.
    * @return array list of data items
    */
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;
}
CSqlDataProvider通过传人的sql,经过db执行获取数据
/**
    * Fetches the data from the persistent data storage.
    * @return array list of data items
    */
protected function fetchData()
{
    $sql=$this->sql;
    $db=$this->db===null ? Yii::app()->db : $this->db;
    $db->active=true;

    if(($sort=$this->getSort())!==false)
    {
        $order=$sort->getOrderBy();
        if(!empty($order))
        {
            if(preg_match('/\s+order\s+by\s+[\w\s,]+$/i',$sql))
                $sql.=', '.$order;
            else
                $sql.=' ORDER BY '.$order;
        }
    }

    if(($pagination=$this->getPagination())!==false)
    {
        $pagination->setItemCount($this->getTotalItemCount());
        $limit=$pagination->getLimit();
        $offset=$pagination->getOffset();
        $sql=$db->getCommandBuilder()->applyLimit($sql,$limit,$offset);
    }

    $command=$db->createCommand($sql);
    foreach($this->params as $name=>$value)
        $command->bindValue($name,$value);

    return $command->queryAll();
}




还没有评论.