Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.