Process functions or files async and in parallel without needing AMP, ReactPHP, RxPHP, Spatie/Fork, Fibers, Pthreads, Parallel, Revolt, Pcntl or Swoole.
Just raw PHP! It is magic! This is not the classical meaning of async like python's or nodejs you're addicted to hear. This is more like an "Async Process", or "Async Multitasking", but you can achieve the same results you expect. Enjoy.
For those who, for some reason, cannot or don't want to use Swoole or Parallel
- Native way + no need to change php.ini
- Easy: just composer install the lib and use it
- Fast to learn
- Fast to use: no need to compile, no need to download pecl extensions
- Operating system agnostic
It uses a combination of:
- serializable-clojure lib
- Symfony/Process lib
- and PHP's native Shmop extension (available in any platform)
First it serializes your closure with its code,
Then it sends to another background process to execute, through shmop
- You got some user data and want to do a heavy processing somewhere without blocking;
- You want to send an email in your own platform without blocking with some data you got before;
- You want to create tons of processes at the same time, not blocking the main process/thread;
- Something will be heavy processed and will took time but your user does not need to know that at the time and don't need/want to wait;
it does not works on MSYS or MINGW shells! However, It will work fine on both Windows (cmd and powershell) and Linux.
See demos/demo.php for examples.
composer require terremoth/php-async
<?php
require_once 'vendor/autoload.php';
use Terremoth\Async\PhpFile;
use Terremoth\Async\Process;
$process = new Process();
$age = 30;
$name = 'John Doe';
$fruits = ['orange', 'apple', 'grape'];
$process->send(function () use ($age, $name, $fruits) {
/*
// Anything you want to process here
// + you can use closure vars for sending data to the other process
*/
});
// Another way to use is if you want to just process a file Asynchronously, you can do this:
$args = ['--verbose', '-n', '123'];
$asyncFile = new PhpFile('existing-php-file.php', $args); // make sure to pass the correct file with its path
$asyncFile->run();
/*
Take care with $args if you will use it this way!
Attackers may explore this to inject commands through RFI/LFI attacks.
The suggestion is: avoid the users to add/control the $args variable.
*/