thinkt4nk
8/10/2011 - 6:37 PM

POC for a iterative model retrieval method for Yii

POC for a iterative model retrieval method for Yii

<?php 

class EIterableActiveRecord extends CActiveRecord 
{
	public function getIter($buffer_size)
	{
		return new ActiveRecordIterator($this,$buffer_size);
	}
}
class ActiveRecordIterator implements Iterator
{
	protected $model;
	protected $index;
	protected $buffer_size;

	public function __construct($model,$buffer_size) 
	{
		$this->model = $model;
		$this->buffer_size = $buffer_size;
		$this->rewind();
	}

	public function rewind()
	{
		$this->index = 0;
	}

	public function current()
	{
		$criteria = $this->getCriteria($this->index);
		return $this->model->findAll($criteria);
	}

	private function getCriteria($index)
	{
		return new CDbCriteria(array(
			'limit' => $this->buffer_size,
			'offset' => ($this->buffer_size * $index),
		));
	}

	public function key()
	{
		return $this->index;
	}

	public function next()
	{
		++$this->index;
	}

	public function valid()
	{
		$models = $this->model->findAll($this->getCriteria($this->index));
		return !empty($models);
	}
}