Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 24 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kalenjordan/5483065 to your computer and use it in GitHub Desktop.
Save kalenjordan/5483065 to your computer and use it in GitHub Desktop.
Batched iterator for Magento collections
// This is how you would use it. Pass in your collection
// along with an individual callback as well as a batch callback
Mage::getSingleton('stcore/resource_iterator_batched')->walk(
$collection,
array($this, 'batchIndividual'),
array($this, 'batchAfter'),
self::BATCH_SIZE
);
public function batchIndividual($model)
{
// Do stuff with the $model
}
public function memberBatchAfter()
{
// Do stuff with the batch. For example if you're preparing a
// batch of records to pipe up to an API, here's where you
// do that.
}
/**
* Batched Iterator
*/
class ST_Core_Model_Resource_Iterator_Batched extends Varien_Object
{
const DEFAULT_BATCH_SIZE = 250;
/**
* @param $collection Varien_Data_Collection
* @param array $callback
*/
public function walk($collection, array $callbackForIndividual, array $callbackAfterBatch, $batchSize = null)
{
if (!$batchSize) {
$batchSize = self::DEFAULT_BATCH_SIZE;
}
$collection->setPageSize($batchSize);
$currentPage = 1;
$pages = $collection->getLastPageNumber();
do {
$collection->setCurPage($currentPage);
$collection->load();
foreach ($collection as $item) {
call_user_func($callbackForIndividual, $item);
}
call_user_func($callbackAfterBatch);
$currentPage++;
$collection->clear();
} while ($currentPage <= $pages);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment