CPdoDataProvider for YII framework

This class place data from SELECT result in CDataProvider

<?php

/*

* CPdoDataProvider class file.

*

* @author Sobol Andrey <andrey.sobol.nn@gmail.com>

* @link http://www.asobol.ru/

* @copyright Copyright &copy; 2010 Sobol Andrey

* @version 1.0

* @license GNU 2.0

*

* Use and sample:

* 1. Place unit in protected/components

* 2. In select result first field need primary key field.

* 3. Sample use. This is function from my class.

*

* public function getSqlProvider($aRubricTr){

* $sql= " select distinct _c.customerid from customer _c, customerinfo _ci, rubric _r";

* $sql.=" where get_root_customerid(_ci.customerid)=_c.rootcustomerid";

* $sql.=" and _ci.isactive and _c.isactive";

* $sql.=" and _r.rubricid=_ci.rubricid";

* $sql.=" and _r.tr <@ '$aRubricTr'";

* $sql.=" and _c.parentid IS NULL"; //collect only root customers

*

* $sqlcount="select count(foo.customerid) from (".$sql.") as foo";

*

* if (!$this->_dpCustomerForRubric){

* $this->_dpCustomerForRubric= new CPdoDataProvider(array(

* 'sql'=>$sql,

* 'sqlcount'=>$sqlcount,

* 'pagination'=>array(

* 'pageSize'=>self::PAGE_CUST_SIZE),

* ));

* }

* return $this->_dpCustomerForRubric;

* }

*/

class CPdoDataProvider extends CDataProvider{

private $_sql;

private $_sqlcount;

private $_id;

private static $_pdoCounter=0;

public function __construct($config)

{

$this->_id='ywPdo'.self::$_pdoCounter++;

$config = new CConfiguration($config);

$config->applyTo($this);

}

public function setSql($sql){

$this->_sql=$sql;

}

public function getSql(){

return $this->_sql;

}

public function setSqlCount($sql){

$this->_sqlcount=$sql;

}

public function getSqlCount(){

return $this->_sqlcount;

}

public function getId()

{

$this->_id;

}

public function setId($value)

{

$this->_id=$value;

}

protected function fetchData() {

$cn=Yii::app()->db;

if(($pagination=$this->getPagination())!==false)

{

$pagination->setItemCount($this->getTotalItemCount());

$limit=$pagination->pageSize;

$offset=$pagination->offset;

$cb=$cn->getCommandBuilder();

$sql_pag=$cb->applyLimit($this->_sql, $limit, $offset);

$cmd=$cn->createCommand($sql_pag);

} else

$cmd=$cn->createCommand($this->_sql);

//if(($sort=$this->getSort())!==false)

// $sort->applyOrder($criteria);

return $cmd->queryAll();

}

public function getSort()

{

/*if(($sort=parent::getSort())!==false)

$sort->modelClass=$this->modelClass;

return $sort;*/

return (parent::getSort());

}

protected function fetchKeys() {

$keys=array();

foreach($this->getData() as $i=>$data){

$r=each($data);

$keys[]=$r[1];

}

return $keys;

}

protected function calculateTotalItemCount() {

//calculate total record count for query

if (isset($this->_sqlcount))

$q_cnt=$this->_sqlcount;

else

$q_cnt="select count(foo.*) from ($this->_sql) as foo";

$cn=Yii::app()->db;

$cmd=$cn->createCommand($q_cnt);

return $cmd->queryScalar();

}

}

?>