|
1 | 1 | <?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Return queue object |
| 5 | + * |
| 6 | + * @return \Leaf\Queue |
| 7 | + */ |
| 8 | +function queue() |
| 9 | +{ |
| 10 | + if (!(\Leaf\Config::getStatic('queue'))) { |
| 11 | + \Leaf\Config::singleton('queue', function () { |
| 12 | + return new \Leaf\Queue(); |
| 13 | + }); |
| 14 | + } |
| 15 | + |
| 16 | + return \Leaf\Config::get('queue'); |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Dispatch a job, batch or a group of jobs |
| 21 | + * |
| 22 | + * @param array|mixed $dispatchable The job, batch or group of jobs to dispatch |
| 23 | + * @param array $data The data to pass to the job |
| 24 | + */ |
| 25 | +function dispatch($dispatchable, $data = []) |
| 26 | +{ |
| 27 | + if (is_array($dispatchable)) { |
| 28 | + foreach ($dispatchable as $item) { |
| 29 | + dispatch($item, $data); |
| 30 | + } |
| 31 | + |
| 32 | + return; |
| 33 | + } |
| 34 | + |
| 35 | + /** @var \Leaf\Queue\Dispatchable */ |
| 36 | + $jobOrBatch = new $dispatchable(); |
| 37 | + $queueModuleConfig = MvcConfig('queue') ?? []; |
| 38 | + $jobConnection = $jobOrBatch->connection(); |
| 39 | + |
| 40 | + $defaultConnection = $queueModuleConfig['connections'][$queueModuleConfig['default'] ?? 'database']; |
| 41 | + |
| 42 | + if (!empty($data)) { |
| 43 | + $jobOrBatch->with($data); |
| 44 | + } |
| 45 | + |
| 46 | + // if (\Leaf\Config::getStatic('queue')) { |
| 47 | + // return queue()->push([ |
| 48 | + // 'class' => $jobOrBatch, |
| 49 | + // 'config' => $jobOrBatch->getConfig(), |
| 50 | + // 'status' => 'pending', |
| 51 | + // 'retry_count' => 0, |
| 52 | + // ]); |
| 53 | + // } |
| 54 | + |
| 55 | + // can optimize by saving a cached version of this instance |
| 56 | + queue()->connect($queueModuleConfig['connections'][$jobConnection] ?? $defaultConnection); |
| 57 | + |
| 58 | + return queue()->push([ |
| 59 | + 'class' => $jobOrBatch::class, |
| 60 | + 'config' => json_encode($jobOrBatch->getConfig()), |
| 61 | + 'status' => 'pending', |
| 62 | + 'retry_count' => 0, |
| 63 | + ]); |
| 64 | +} |
0 commit comments