Forked from kalenjordan/Batched Iterator for Magento collections
Created
March 28, 2018 13:42
-
-
Save diazwatson/b9c69313e377442ba3845eebebb5d2ec to your computer and use it in GitHub Desktop.
Batched iterator for Magento collections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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. | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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