Created
January 20, 2017 10:46
-
-
Save nojimage/2568d4140ffea1b7ccdf89a32ade6475 to your computer and use it in GitHub Desktop.
CakePHP 2.x findEach
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
<?php | |
/** | |
* 検索結果に対して処理を行う | |
* | |
* example: | |
* $model->findEach(['conditions' => ['status' => 1]], function ($data) { | |
* // $data = ['Model' => [ ... ]] | |
* debug($data); | |
* }); | |
* | |
* @param array $options findオプション | |
* @param callable $func 適用する処理 | |
* @param integer $window 一度のfindで取得処理する件数 | |
*/ | |
public function findEach(array $options, callable $func, $window = 100) | |
{ | |
$limit = isset($options['limit']) ? $options['limit'] : 0; | |
$count = 0; | |
$options += ['offset' => 0]; | |
$options['limit'] = $window; | |
while ($results = $this->find('all', $options)) { | |
$processCount = $count + count($results); | |
// 全て処理したら limit を超える場合は、対象を切り詰める | |
if ($limit > 0 && $limit < $processCount) { | |
$results = array_slice($results, 0, $processCount - $limit); | |
} | |
foreach ($results as $result) { | |
call_user_func($func, $result); | |
$count++; | |
} | |
$options['offset'] += $window; | |
if ($limit > 0 && $limit <= $count) { | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment