Skip to content

Vectorial1024/laravel-process-async

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

28 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

laravel-process-async

Packagist License Packagist Version Packagist Downloads PHP Dependency Version GitHub Repo Stars

Utilize Laravel Processes to run PHP code asynchronously.

What really is this?

Laravel Processes was first introduced in Laravel 10. This library wraps around Process::start() to let you execute code in the background to achieve async, albeit with some caveats:

  • You may only execute PHP code
  • Restrictions from laravel/serializable-closure apply (see their README)
  • Hands-off execution: no built-in result-checking, check the results yourself (e.g. via database, file cache, etc)

Why should I want this?

This library is very helpful for these cases:

  • You want a minimal-setup async for easy vertical scaling
  • You want to start quick-and-dirty async tasks right now (e.g. prefetching resources, pinging remote, etc.)
    • Best is if your task only has very few lines of code

Of course, if you are considering extreme scaling (e.g. Redis queues in Laravel, multi-worker clusters, etc.) or guaranteed task execution, then this library is obviously not for you.

Installation

via Composer:

composer require vectorial1024/laravel-process-async

Change log

Please see CHANGELOG.md.

Example code

Tasks can be defined as PHP closures, or (recommended) as an instance of a class that implements AsyncTaskInterface.

A very simple example task to write Hello World to a file:

// define the task...
$target = "document.txt";
$task = new AsyncTask(function () use ($target) {
    $fp = fopen($target, "w");
    fwrite($fp, "Hello World!!");
    fflush($fp);
    fclose($fp);
});

// if you are using interfaces, then it is just like this:
// $task = new AsyncTask(new WriteToFileTask($target, $message));

// then start it.
$task->start();

// the task is now run in another PHP process, and will not report back to this PHP process.

Testing

PHPUnit via Composer script:

composer run-script test

Latest results of cross-platform core testing:

Runtime Ubuntu Windows
Laravel 10 (PHP 8.1) Build-U-L10-PHP80100 Build-W-L10-PHP80100
Laravel 11 (PHP 8.2) Build-U-L11-PHP80200 Build-W-L11-PHP80200
Laravel 12 (PHP ???) 🛠️ 🛠️