PluginProbe
Imagify Image Optimization: Optimize Images | Compress & Convert to WebP/AVIF / 2.3.3
Imagify Image Optimization: Optimize Images | Compress & Convert to WebP/AVIF v2.3.3
2.3.4 2.3.3 2.3.2 2.3.1 2.3.0 2.2.9 2.2.8 trunk 1.10 1.3.3 1.3.4 1.3.5 1.3.5.1 1.3.5.2 1.3.6 1.3.6.1 1.4 1.4.1 1.4.2 1.4.3 1.4.4 1.4.5 1.4.6 1.4.7 1.5 All 103 releases
imagify / vendor / deliciousbrains / wp-background-processing / README.md

README.md in Imagify Image Optimization: Optimize Images | Compress & Convert to WebP/AVIF 2.3.3, at vendor/deliciousbrains/wp-background-processing/README.md

439 lines 14.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 # WP Background Processing
2
3 WP Background Processing can be used to fire off non-blocking asynchronous requests or as a background processing tool, allowing you to queue tasks. Check out the [](https://github.com/A5hleyRich/wp-background-processing-exampleexample plugin](https://github.com/A5hleyRich/wp-background-processing-example](https://github.com/A5hleyRich/wp-background-processing-example) or read the [](https://deliciousbrains.com/background-processing-wordpress/accompanying article](https://deliciousbrains.com/background-processing-wordpress/](https://deliciousbrains.com/background-processing-wordpress/).
4
5 Inspired by [](https://github.com/techcrunch/wp-async-taskTechCrunch WP Asynchronous Tasks](https://github.com/techcrunch/wp-async-task](https://github.com/techcrunch/wp-async-task).
6
7 __Requires PHP 5.6+__
8
9 ## Install
10
11 The recommended way to install this library in your project is by loading it through Composer:
12
13 ```shell
14 composer require deliciousbrains/wp-background-processing
15 ```
16
17 It is highly recommended to prefix wrap the library class files using [](https://packagist.org/packages/coenjacobs/mozartthe Mozart package](https://packagist.org/packages/coenjacobs/mozart](https://packagist.org/packages/coenjacobs/mozart), to prevent collisions with other projects using this same library.
18
19 ## Usage
20
21 ### Async Request
22
23 Async requests are useful for pushing slow one-off tasks such as sending emails to a background process. Once the request has been dispatched it will process in the background instantly.
24
25 Extend the `WP_Async_Request` class:
26
27 ```php
28 class WP_Example_Request extends WP_Async_Request {
29
30 /**
31 * @var string
32 */
33 protected $prefix = 'my_plugin';
34
35 /**
36 * @var string
37 */
38 protected $action = 'example_request';
39
40 /**
41 * Handle a dispatched request.
42 *
43 * Override this method to perform any actions required
44 * during the async request.
45 */
46 protected function handle() {
47 // Actions to perform.
48 }
49
50 }
51 ```
52
53 #### `protected $prefix`
54
55 Should be set to a unique prefix associated with your plugin, theme, or site's custom function prefix.
56
57 #### `protected $action`
58
59 Should be set to a unique name.
60
61 #### `protected function handle()`
62
63 Should contain any logic to perform during the non-blocking request. The data passed to the request will be accessible via `$_POST`.
64
65 #### Dispatching Requests
66
67 Instantiate your request:
68
69 ```php
70 $this->example_request = new WP_Example_Request();
71 ```
72
73 Add data to the request if required:
74
75 ```php
76 $this->example_request->data( array( 'value1' => $value1, 'value2' => $value2 ) );
77 ```
78
79 Fire off the request:
80
81 ```php
82 $this->example_request->dispatch();
83 ```
84
85 Chaining is also supported:
86
87 ```php
88 $this->example_request->data( array( 'data' => $data ) )->dispatch();
89 ```
90
91 ### Background Process
92
93 Background processes work in a similar fashion to async requests, but they allow you to queue tasks. Items pushed onto the queue will be processed in the background once the queue has been saved and dispatched. Queues will also scale based on available server resources, so higher end servers will process more items per batch. Once a batch has completed, the next batch will start instantly.
94
95 Health checks run by default every 5 minutes to ensure the queue is running when queued items exist. If the queue has failed it will be restarted.
96
97 Queues work on a first in first out basis, which allows additional items to be pushed to the queue even if it’s already processing. Saving a new batch of queued items and dispatching while another background processing instance is already running will result in the dispatch shortcutting out and the existing instance eventually picking up the new items and processing them when it is their turn.
98
99 Extend the `WP_Background_Process` class:
100
101 ```php
102 class WP_Example_Process extends WP_Background_Process {
103
104 /**
105 * @var string
106 */
107 protected $prefix = 'my_plugin';
108
109 /**
110 * @var string
111 */
112 protected $action = 'example_process';
113
114 /**
115 * Perform task with queued item.
116 *
117 * Override this method to perform any actions required on each
118 * queue item. Return the modified item for further processing
119 * in the next pass through. Or, return false to remove the
120 * item from the queue.
121 *
122 * @param mixed $item Queue item to iterate over.
123 *
124 * @return mixed
125 */
126 protected function task( $item ) {
127 // Actions to perform.
128
129 return false;
130 }
131
132 /**
133 * Complete processing.
134 *
135 * Override if applicable, but ensure that the below actions are
136 * performed, or, call parent::complete().
137 */
138 protected function complete() {
139 parent::complete();
140
141 // Show notice to user or perform some other arbitrary task...
142 }
143
144 }
145 ```
146
147 #### `protected $prefix`
148
149 Should be set to a unique prefix associated with your plugin, theme, or site's custom function prefix.
150
151 #### `protected $action`
152
153 Should be set to a unique name.
154
155 #### `protected function task( $item )`
156
157 Should contain any logic to perform on the queued item. Return `false` to remove the item from the queue or return `$item` to push it back onto the queue for further processing. If the item has been modified and is pushed back onto the queue the current state will be saved before the batch is exited.
158
159 #### `protected function complete()`
160
161 Optionally contain any logic to perform once the queue has completed.
162
163 #### Dispatching Processes
164
165 Instantiate your process:
166
167 ```php
168 $this->example_process = new WP_Example_Process();
169 ```
170
171 **Note:** You must instantiate your process unconditionally. All requests should do this, even if nothing is pushed to the queue.
172
173 Push items to the queue:
174
175 ```php
176 foreach ( $items as $item ) {
177 $this->example_process->push_to_queue( $item );
178 }
179 ```
180
181 An item can be any valid PHP value, string, integer, array or object. If needed, the $item is serialized when written to the database.
182
183 Save and dispatch the queue:
184
185 ```php
186 $this->example_process->save()->dispatch();
187 ```
188
189 #### Handling serialized objects in queue items
190
191 Queue items that contain non-scalar values are serialized when stored in the database. To avoid potential security issues during unserialize, this library provides the option to set the `allowed_classes` option when calling `unserialize()` which limits which classes can be instantiated. It's kept internally as the protected `$allowed_batch_data_classes` property.
192
193 To maintain backward compatibility the default value is `true`, meaning that any serialized object will be instantiated. Please note that this default behavior may change in a future major release.
194
195 We encourage all users of this library to take advantage of setting a strict value for `$allowed_batch_data_classes`. If possible, set the value to `false` to disallow any objects from being instantiated, or a very limited list of class names, see examples below.
196
197 Objects in the serialized string that are not allowed to be instantiated will instead get the class type `__PHP_Incomplete_Class`.
198
199 ##### Overriding the default `$allowed_batch_data_classes`
200
201 The default behavior can be overridden by passing an array of allowed classes to the constructor:
202
203 ``` php
204 $allowed_batch_data_classes = array( MyCustomItem::class, MyItemHelper::class );
205 $this->example_process = new WP_Example_Process( $allowed_batch_data_classes );
206 ```
207
208 Or, set the value to `false`:
209
210 ``` php
211 $this->example_process = new WP_Example_Process( false );
212 ```
213
214
215 Another way to change the default is to override the `$allowed_batch_data_classes` property in your process class:
216
217 ``` php
218 class WP_Example_Process extends WP_Background_Process {
219
220 /**
221 * @var string
222 */
223 protected $prefix = 'my_plugin';
224
225 /**
226 * @var string
227 */
228 protected $action = 'example_process';
229
230 /**
231 *
232 * @var bool|array
233 */
234 protected $allowed_batch_data_classes = array( MyCustomItem::class, MyItemHelper::class );
235 ...
236
237 ```
238
239 #### Background Process Status
240
241 A background process can be queued, processing, paused, cancelled, or none of the above (not started or has completed).
242
243 ##### Queued
244
245 To check whether a background process has queued items use `is_queued()`.
246
247 ```php
248 if ( $this->example_process->is_queued() ) {
249 // Do something because background process has queued items, e.g. add notice in admin UI.
250 }
251 ```
252
253 ##### Processing
254
255 To check whether a background process is currently handling a queue of items use `is_processing()`.
256
257 ```php
258 if ( $this->example_process->is_processing() ) {
259 // Do something because background process is running, e.g. add notice in admin UI.
260 }
261 ```
262
263 ##### Paused
264
265 You can pause a background process with `pause()`.
266
267 ```php
268 $this->example_process->pause();
269 ```
270
271 The currently processing batch will continue until it either completes or reaches the time or memory limit. At that point it'll unlock the process and either complete the batch if the queue is empty, or perform a dispatch that will result in the handler removing the healthcheck cron and firing a "paused" action.
272
273 To check whether a background process is currently paused use `is_paused()`.
274
275 ```php
276 if ( $this->example_process->is_paused() ) {
277 // Do something because background process is paused, e.g. add notice in admin UI.
278 }
279 ```
280
281 You can perform an action in response to background processing being paused by handling the "paused" action for the background process's identifier ($prefix + $action).
282
283 ```php
284 add_action( 'my_plugin_example_process_paused', function() {
285 // Do something because background process is paused, e.g. add notice in admin UI.
286 });
287 ```
288
289 You can resume a background process with `resume()`.
290
291 ```php
292 $this->example_process->resume();
293 ```
294
295 You can perform an action in response to background processing being resumed by handling the "resumed" action for the background process's identifier ($prefix + $action).
296
297 ```php
298 add_action( 'my_plugin_example_process_resumed', function() {
299 // Do something because background process is resumed, e.g. add notice in admin UI.
300 });
301 ```
302
303 ##### Cancelled
304
305 You can cancel a background process with `cancel()`.
306
307 ```php
308 $this->example_process->cancel();
309 ```
310
311 The currently processing batch will continue until it either completes or reaches the time or memory limit. At that point it'll unlock the process and either complete the batch if the queue is empty, or perform a dispatch that will result in the handler removing the healthcheck cron, deleting all batches of queued items and firing a "cancelled" action.
312
313 To check whether a background process is currently cancelled use `is_cancelled()`.
314
315 ```php
316 if ( $this->example_process->is_cancelled() ) {
317 // Do something because background process is cancelled, e.g. add notice in admin UI.
318 }
319 ```
320
321 You can perform an action in response to background processing being cancelled by handling the "cancelled" action for the background process's identifier ($prefix + $action).
322
323 ```php
324 add_action( 'my_plugin_example_process_cancelled', function() {
325 // Do something because background process is paused, e.g. add notice in admin UI.
326 });
327 ```
328
329 The "cancelled" action fires once the queue has been cleared down and cancelled status removed. After which `is_cancelled()` will no longer be true as the background process is now dormant.
330
331 ##### Active
332
333 To check whether a background process has queued items, is processing, is paused, or is cancelling, use `is_active()`.
334
335 ```php
336 if ( $this->example_process->is_active() ) {
337 // Do something because background process is active, e.g. add notice in admin UI.
338 }
339 ```
340
341 If a background process is not active, then it either has not had anything queued yet and not started, or has finished processing all queued items.
342
343 ### BasicAuth
344
345 If your site is behind BasicAuth, both async requests and background processes will fail to complete. This is because WP Background Processing relies on the [](https://developer.wordpress.org/plugins/http-api/WordPress HTTP API](https://developer.wordpress.org/plugins/http-api/](https://developer.wordpress.org/plugins/http-api/), which requires you to attach your BasicAuth credentials to requests. The easiest way to do this is using the following filter:
346
347 ```php
348 function wpbp_http_request_args( $r, $url ) {
349 $r['headers']['Authorization'] = 'Basic ' . base64_encode( USERNAME . ':' . PASSWORD );
350
351 return $r;
352 }
353 add_filter( 'http_request_args', 'wpbp_http_request_args', 10, 2);
354 ```
355
356 ## Contributing
357
358 Contributions are welcome via Pull Requests, but please do raise an issue before
359 working on anything to discuss the change if there isn't already an issue. If there
360 is an approved issue you'd like to tackle, please post a comment on it to let people know
361 you're going to have a go at it so that effort isn't wasted through duplicated work.
362
363 ### Unit & Style Tests
364
365 When working on the library, please add unit tests to the appropriate file in the
366 `tests` directory that cover your changes.
367
368 #### Setting Up
369
370 We use the standard WordPress test libraries for running unit tests.
371
372 Please run the following command to set up the libraries:
373
374 ```shell
375 bin/install-wp-tests.sh db_name db_user db_pass
376 ```
377
378 Substitute `db_name`, `db_user` and `db_pass` as appropriate.
379
380 Please be aware that running the unit tests is a **destructive operation**, *database
381 tables will be cleared*, so please use a database name dedicated to running unit tests.
382 The standard database name usually used by the WordPress community is `wordpress_test`, e.g.
383
384 ```shell
385 bin/install-wp-tests.sh wordpress_test root root
386 ```
387
388 Please refer to the [](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/#3-initialize-the-testing-environment-locallyInitialize the testing environment locally](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/#3-initialize-the-testing-environment-locally](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/#3-initialize-the-testing-environment-locally)
389 section of the WordPress Handbook's [](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/Plugin Integration Tests](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/](https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests/)
390 entry should you run into any issues.
391
392 #### Running Unit Tests
393
394 To run the unit tests, simply run:
395
396 ```shell
397 make test-unit
398 ```
399
400 If the `composer` dependencies aren't in place, they'll be automatically installed first.
401
402 #### Running Style Tests
403
404 It's important that the code in the library use a consistent style to aid in quickly
405 understanding it, and to avoid some common issues. `PHP_Code_Sniffer` is used with
406 mostly standard WordPress rules to help check for consistency.
407
408 To run the style tests, simply run:
409
410 ```shell
411 make test-style
412 ```
413
414 If the `composer` dependencies aren't in place, they'll be automatically installed first.
415
416 #### Running All Tests
417
418 To make things super simple, just run the following to run all tests:
419
420 ```shell
421 make
422 ```
423
424 If the `composer` dependencies aren't in place, they'll be automatically installed first.
425
426 #### Creating a PR
427
428 When creating a PR, please make sure to mention which GitHub issue is being resolved
429 at the top of the description, e.g.:
430
431 `Resolves #123`
432
433 The unit and style tests will be run automatically, the PR will not be eligible for
434 merge unless they pass, and the branch is up-to-date with `master`.
435
436 ## License
437
438 [](http://www.gnu.org/licenses/gpl-2.0.htmlGPLv2+](http://www.gnu.org/licenses/gpl-2.0.html](http://www.gnu.org/licenses/gpl-2.0.html)
439