Created
March 18, 2017 01:15
-
-
Save yang-wei/9726c1a03ce498023753fda5a1431332 to your computer and use it in GitHub Desktop.
Chukify - PHP utils to break function with large array parameter into multiple calls and combine the result
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 | |
class Helper { | |
/** | |
* Break up process for function with first large array parameter into multiple time and merge | |
* Can be useful when thing are slow querying database or requesting api with large size of array at once | |
*/ | |
public static function chunkify(callable $fn, array $fnFirstParam = [], $chunkSize=1000, ...$fnRestParams) { | |
$result = []; | |
foreach (array_chunk($fnFirstParam, $chunkSize) as $chunk) { | |
$result = array_merge($result, $fn($chunk, ...$fnRestParams)); | |
} | |
return $result; | |
} | |
} |
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 | |
class Report | |
{ | |
private $header = 'Amount'; | |
public function get($rawReport, $prefix, $separator) { | |
return array_map($this->formatter($prefix, $separator), $rawReport); | |
} | |
private function formatter($prefix, $separator) { | |
return function ($row) use ($prefix, $separator) { | |
return $this->header . $prefix . $row . $separator; | |
}; | |
} | |
} | |
// use it | |
$rawReport = ['a', 'b', 'c']; | |
$prefix = ' : '; | |
$separator = '<br />'; | |
$result = Helper::chunkify([new Report, 'get'], $rawReport, 1000, $prefix, $separator); | |
var_dump($result); |
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 | |
class Call3rdPartyAPI | |
{ | |
public function getUsersInfo($userList) { | |
// call api | |
return $userList; | |
} | |
} | |
// let's say this 3rd party api has limit on calling this function on $userList with maximum length of 100 | |
// and we have 1000 in our user list | |
$3rdPartyApiParamLimit = 100; | |
$result = Helper::chunkify([new Call3rdPartyAPI, 'getUsersInfo'], $1000UsersList, $3rdPartyApiParamLimit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment