22
33## Introduction
44
5- ` friendsofhyperf/async-queue-closure-job ` is an asynchronous queue closure job component for Hyperf. It allows you to execute closures as background tasks, with full support for dependency injection and fluent configuration, making the use of asynchronous tasks simpler and more elegant.
5+ ` friendsofhyperf/async-queue-closure-job ` is an async queue closure job component for Hyperf. It allows you to execute closures as background jobs with full support for dependency injection and fluent configuration, making async tasks simpler and more elegant.
66
7- Unlike traditional methods that require creating task classes, this component enables you to define task logic directly using closures, eliminating the need for additional class files and resulting in cleaner code.
7+ Unlike traditional job classes, this component lets you define job logic directly with closures, eliminating the need for extra class files and making your code more concise .
88
99## Installation
1010
@@ -14,26 +14,26 @@ composer require friendsofhyperf/async-queue-closure-job
1414
1515## Basic Usage
1616
17- ### Simple Closure Task
17+ ### Simple Closure Job
1818
1919``` php
2020use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
2121
22- // Dispatch a simple closure task
22+ // Dispatch a simple closure job
2323dispatch(function () {
24- // Your task logic
24+ // Your job logic here
2525 var_dump('Hello from closure job!');
2626});
2727```
2828
29- ### Setting Maximum Attempts
29+ ### Set Maximum Attempts
3030
3131``` php
3232use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
3333
3434// Set maximum attempts (retry limit)
3535dispatch(function () {
36- // Your task logic
36+ // Your job logic here
3737 // If it fails, it will retry up to 3 times
3838})->setMaxAttempts(3);
3939```
@@ -42,59 +42,59 @@ dispatch(function () {
4242
4343### Fluent API Configuration
4444
45- You can flexibly configure various task options through method chaining:
45+ You can flexibly configure various options using method chaining:
4646
4747``` php
4848use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
4949
5050// Chain multiple configuration options
5151dispatch(function () {
52- // Your task logic
52+ // Your job logic here
5353})
54- ->onConnection ('high-priority') // Specify queue connection
54+ ->onPool ('high-priority') // Specify queue connection
5555 ->delay(60) // Delay execution by 60 seconds
56- ->setMaxAttempts(5); // Maximum of 5 retries
56+ ->setMaxAttempts(5); // Retry up to 5 times
5757```
5858
59- ### Specifying Queue Connection
59+ ### Specifying Queue Connections
6060
61- When you have multiple queue connections, you can specify which connection the task should use:
61+ When you have multiple queue connections, you can specify which connection to use:
6262
6363``` php
6464use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
6565
66- // Use specified queue connection
66+ // Use a specific queue connection
6767dispatch(function () {
68- // High- priority task logic
69- })->onConnection ('high-priority');
68+ // High priority task logic
69+ })->onPool ('high-priority');
7070
71- // Or use the onPool method (alias)
71+ // Alternative pool name
7272dispatch(function () {
73- // Low- priority task logic
73+ // Low priority task logic
7474})->onPool('low-priority');
7575```
7676
7777### Delayed Execution
7878
79- You can set tasks to execute after a certain period :
79+ You can set a delay before the task starts executing :
8080
8181``` php
8282use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
8383
84- // Execute after 60 seconds delay
84+ // Delay execution by 60 seconds
8585dispatch(function () {
86- // Your task logic
86+ // Your job logic here
8787})->delay(60);
8888
89- // Execute after 5 minutes delay
89+ // Delay execution by 5 minutes
9090dispatch(function () {
91- // Your task logic
91+ // Your job logic here
9292})->delay(300);
9393```
9494
9595### Conditional Execution
9696
97- Use the ` when ` and ` unless ` methods to dynamically configure tasks based on conditions:
97+ Use ` when ` and ` unless ` methods to dynamically configure tasks based on conditions:
9898
9999``` php
100100use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
@@ -103,26 +103,26 @@ $isUrgent = true;
103103
104104// Execute callback only when condition is true
105105dispatch(function () {
106- // Your task logic
106+ // Your job logic here
107107})
108108 ->when($isUrgent, function ($dispatch) {
109- $dispatch->onConnection ('urgent');
109+ $dispatch->onPool ('urgent');
110110 });
111111
112112// Execute callback only when condition is false
113113dispatch(function () {
114- // Your task logic
114+ // Your job logic here
115115})
116116 ->unless($isUrgent, function ($dispatch) {
117- $dispatch->delay(300 );
117+ $dispatch->delay(30 );
118118 });
119119
120- // Combined usage
120+ // Combine usage
121121dispatch(function () {
122- // Your task logic
122+ // Your job logic here
123123})
124124 ->when($isUrgent, function ($dispatch) {
125- $dispatch->onConnection ('urgent');
125+ $dispatch->onPool ('urgent');
126126 })
127127 ->unless($isUrgent, function ($dispatch) {
128128 $dispatch->delay(60);
@@ -131,7 +131,7 @@ dispatch(function () {
131131
132132### Dependency Injection
133133
134- Closure tasks fully support Hyperf's dependency injection functionality . You can declare required dependencies in the closure parameters:
134+ Closure jobs fully support Hyperf's dependency injection. You can declare required dependencies as closure parameters:
135135
136136``` php
137137use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
@@ -142,9 +142,9 @@ use Psr\Log\LoggerInterface;
142142dispatch(function (UserService $userService, LoggerInterface $logger) {
143143 $users = $userService->getActiveUsers();
144144 $logger->info('Processing ' . count($users) . ' users');
145-
145+
146146 foreach ($users as $user) {
147- // Process user ...
147+ // Process users ...
148148 }
149149});
150150```
@@ -159,17 +159,17 @@ use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
159159$userId = 123;
160160$action = 'update';
161161
162- // Using captured variables
162+ // Use captured variables
163163dispatch(function (UserService $userService) use ($userId, $action) {
164164 $user = $userService->find($userId);
165-
165+
166166 if ($action === 'update') {
167167 $userService->update($user);
168168 }
169169})->setMaxAttempts(3);
170170```
171171
172- ## Practical Application Scenarios
172+ ## Real-World Use Cases
173173
174174### Sending Notifications
175175
@@ -181,7 +181,7 @@ dispatch(function (NotificationService $notification) use ($userId, $message) {
181181})->setMaxAttempts(3);
182182```
183183
184- ### Processing File Uploads
184+ ### File Upload Processing
185185
186186``` php
187187use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
@@ -200,7 +200,7 @@ use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
200200dispatch(function (StatisticsService $stats) use ($date) {
201201 $stats->calculateDailyReport($date);
202202 $stats->sendReport($date);
203- })->onConnection ('statistics');
203+ })->onPool ('statistics');
204204```
205205
206206### Batch Operations
@@ -221,10 +221,10 @@ foreach ($userIds as $userId) {
221221
222222### ` dispatch(Closure $closure): PendingAsyncQueueDispatch `
223223
224- The main dispatch function used to create closure tasks .
224+ The main dispatch function that creates a closure job .
225225
226226** Parameters:**
227- - ` $closure ` - The closure to be executed
227+ - ` $closure ` - The closure to execute
228228
229229** Returns:**
230230- ` PendingAsyncQueueDispatch ` - Pending closure dispatch object
@@ -239,85 +239,85 @@ Set the queue connection name.
239239- ` $connection ` - Queue connection name
240240
241241** Returns:**
242- - ` static ` - Current object, supports method chaining
242+ - ` static ` - Current object for method chaining
243243
244244#### ` onPool(string $pool): static `
245245
246- Set the queue connection name (alias of ` onConnection ` ).
246+ Set the queue connection name (alias for ` onConnection ` ).
247247
248248** Parameters:**
249249- ` $pool ` - Queue connection name
250250
251251** Returns:**
252- - ` static ` - Current object, supports method chaining
252+ - ` static ` - Current object for method chaining
253253
254254#### ` delay(int $delay): static `
255255
256- Set the delay execution time.
256+ Set the delay time before execution .
257257
258258** Parameters:**
259259- ` $delay ` - Delay time in seconds
260260
261261** Returns:**
262- - ` static ` - Current object, supports method chaining
262+ - ` static ` - Current object for method chaining
263263
264264#### ` setMaxAttempts(int $maxAttempts): static `
265265
266- Set the maximum number of retry attempts.
266+ Set the maximum retry attempts.
267267
268268** Parameters:**
269- - ` $maxAttempts ` - Maximum number of attempts
269+ - ` $maxAttempts ` - Maximum attempts
270270
271271** Returns:**
272- - ` static ` - Current object, supports method chaining
272+ - ` static ` - Current object for method chaining
273273
274274#### ` when($condition, $callback): static `
275275
276276Execute callback when condition is true.
277277
278278** Parameters:**
279- - ` $condition ` - Conditional expression
279+ - ` $condition ` - Condition expression
280280- ` $callback ` - Callback function that receives the current object as parameter
281281
282282** Returns:**
283- - ` static ` - Current object, supports method chaining
283+ - ` static ` - Current object for method chaining
284284
285285#### ` unless($condition, $callback): static `
286286
287287Execute callback when condition is false.
288288
289289** Parameters:**
290- - ` $condition ` - Conditional expression
290+ - ` $condition ` - Condition expression
291291- ` $callback ` - Callback function that receives the current object as parameter
292292
293293** Returns:**
294- - ` static ` - Current object, supports method chaining
294+ - ` static ` - Current object for method chaining
295295
296296## Supported Closure Types
297297
298- This component supports the following types of closures :
298+ This component supports the following closure types :
299299
300300- ✅ Simple closures without parameters
301301- ✅ Closures with dependency injection
302- - ✅ Closures using captured variables (` use ` )
302+ - ✅ Closures with captured variables (` use ` )
303303- ✅ Closures with nullable parameters
304- - ✅ Closures mixing dependency injection and captured variables
304+ - ✅ Mixing dependency injection and captured variables
305305
306306## Notes
307307
308- 1 . ** Serialization Limitations** : Closures are serialized for storage, therefore:
309- - Cannot capture unserializable resources (such as database connections, file handles, etc. )
308+ 1 . ** Serialization Limitations** : Closures are serialized before storage, therefore:
309+ - Cannot capture non-serializable resources (e.g., database connections, file handles)
310310 - Captured objects should be serializable
311311
312- 2 . ** Dependency Injection** : Dependencies in closures are resolved from the container when the task executes and are not serialized
312+ 2 . ** Dependency Injection** : Dependencies in closures will be resolved from the container when the job executes, not serialized
313313
314- 3 . ** Asynchronous Execution** : Tasks are executed asynchronously; the dispatch function returns immediately without waiting for task completion
314+ 3 . ** Async Execution** : Tasks execute asynchronously. The dispatch function returns immediately without waiting for task completion
315315
316- 4 . ** Error Handling** : Failed task executions will be retried according to the number of attempts set by ` setMaxAttempts `
316+ 4 . ** Error Handling** : Failed tasks will retry according to the ` setMaxAttempts ` configuration
317317
318318## Configuration
319319
320- This component uses Hyperf's asynchronous queue configuration. You can configure queue parameters in ` config/autoload/async_queue.php ` :
320+ This component uses Hyperf's async queue configuration. You can configure queue parameters in ` config/autoload/async_queue.php ` :
321321
322322``` php
323323<?php
@@ -340,12 +340,12 @@ return [
340340composer test:unit -- tests/AsyncQueueClosureJob
341341```
342342
343- ## Comparison with Traditional Task Classes
343+ ## Comparison with Traditional Job Classes
344344
345345### Traditional Approach
346346
347347``` php
348- // Need to create task class
348+ // Need to create a job class
349349class SendNotificationJob extends Job
350350{
351351 public function __construct(public int $userId, public string $message)
@@ -359,28 +359,28 @@ class SendNotificationJob extends Job
359359 }
360360}
361361
362- // Dispatch task
362+ // Dispatch job
363363$driver->push(new SendNotificationJob($userId, $message));
364364```
365365
366- ### Using Closure Tasks
366+ ### Using Closure Jobs
367367
368368``` php
369369use function FriendsOfHyperf\AsyncQueueClosureJob\dispatch;
370370
371- // Use closure directly , no need to create class
371+ // Directly use closure , no need to create a class
372372dispatch(function (NotificationService $notification) use ($userId, $message) {
373373 $notification->send($userId, $message);
374374});
375375```
376376
377- Advantages of closure tasks :
378- - Cleaner code, no need for additional class files
379- - Better readability with task logic located at dispatch point
380- - Full support for dependency injection
377+ Advantages of closure jobs :
378+ - Cleaner code, no need to create extra class files
379+ - Better readability, job logic is right where it's dispatched
380+ - Full dependency injection support
381381- Flexible fluent API configuration
382382
383383## Related Components
384384
385- - [ hyperf/async-queue] ( https://hyperf.wiki/3.1/#/en /async-queue ) - Hyperf Async Queue
386- - [ friendsofhyperf/closure-job] ( https://github.com/friendsofhyperf/components/tree/main/src/closure-job ) - General Closure Job Component
385+ - [ hyperf/async-queue] ( https://hyperf.wiki/3.1/#/zh-cn /async-queue ) - Hyperf Async Queue
386+ - [ friendsofhyperf/closure-job] ( https://github.com/friendsofhyperf/components/tree/main/src/closure-job ) - Generic Closure Job Component
0 commit comments