Last active
August 12, 2019 21:31
-
-
Save FatBoyXPC/0d44c802494d77d09c3470d81da22772 to your computer and use it in GitHub Desktop.
callback example
This file contains hidden or 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 Foo | |
| { | |
| public function checkFacebookCode($jobId) | |
| { | |
| return $this->checkCode($jobId, function ($job) { | |
| return $job->facebook->sortByDesc('id')->first()->checkForCodeAtUrl(); | |
| }); | |
| } | |
| private function checkCode($jobId, $callback) | |
| { | |
| $job = Job::findOrFail($jobId); | |
| $response = []; | |
| try { | |
| $response['code_found'] = $callback($job); | |
| $status = 200; | |
| } catch (Exception $e) { | |
| $status = 500; | |
| } | |
| return response()->json($response, $status); | |
| } | |
| public function checkRemarketingCode($jobId) | |
| { | |
| return $this->checkCode($jobId, function ($job) { | |
| return $job->remarketing->sortByDesc('id')->first()->checkForCodeAtUrl(); | |
| }); | |
| } | |
| // from another project: | |
| public function updateRecords($beforeCallback, $afterCallback) | |
| { | |
| $db = Database::factory()->mysqli(); | |
| $table = Payment::$TABLE; | |
| $sql = "UPDATE {$table} SET type = '%s' where id = %s"; | |
| $this->walkRecords(function ($record) use ($db, $sql, $beforeCallback, $afterCallback) { | |
| $beforeCallback($record); | |
| $payment = new Payment; | |
| $payment->id = $record['id']; | |
| $payment->type = $record['type']; | |
| $payment->token_id = $record['token_id']; | |
| $payment->card_type = $record['card_type']; | |
| $query = sprintf($sql, $payment->getPaymentType(), $payment->getId()); | |
| $result = $db->query($query); | |
| $afterCallback($record); | |
| // Hoping that GC might pick this up and we don't blow up memory | |
| unset($payment, $record); | |
| }); | |
| } | |
| public function walkRecords($callback) | |
| { | |
| $payments = []; | |
| $db = Database::factory()->mysqli(); | |
| $query = $db->query($this->sql()); | |
| while ($row = mysqli_fetch_assoc($query)) { | |
| $callback($row); | |
| } | |
| } | |
| protected function execute(InputInterface $input, OutputInterface $output) | |
| { | |
| set_time_limit(0); | |
| $beforeCallback = function ($record) use ($output) { | |
| $output->writeln("Starting: {$record['id']}"); | |
| }; | |
| $afterCallback = function ($record) use ($output) { | |
| $output->writeln("Finished: {$record['id']}"); | |
| }; | |
| $this->updateRecords($beforeCallback, $afterCallback); | |
| return 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment