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();
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章