Skip to content

terremoth/php-async

Repository files navigation

PHP Async Process

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!

Psalm type coverage Psalm level Test Run Status Codacy Badge Maintainability License Packagist Downloads

Target Audience

For those who, for some reason, cannot or don't want to use Swoole or Parallel

Why?

  • 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

How?

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

Some Possible Use Cases

  • You got some user data and want to do a heavy processing somewhere without blocking;
  • You want to send an email in you 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;

Warning

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.

Installation

composer require terremoth/php-async

Documentation

<?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.
*/

About

Async and Parallel Processing with PHP with no threads or reactive libs

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages