DEV Community

Cover image for Run artisan command instantly in the background using Symfony process component
Faisal Shaikh
Faisal Shaikh

Posted on

Run artisan command instantly in the background using Symfony process component

Sometimes we want to optimize an API response time but we can't optimize it because the API has operations that can't be moved to background jobs, we need to perform them in the foreground.

In this type of situation, the Symfony process component can help.

When the API is called, we will perform the most important steps like creating/updating main table records, rest of the steps can be moved to an artisan command which will be run instantly in the background using the Symfony process component.

Code:

function runBackgroundProcess($command, $data)
{
 $phpBinaryFinder = new PhpExecutableFinder();

 $phpBinaryPath = $phpBinaryFinder->find();

 $process = new Process ([$phpBinaryPath, base_path('artisan'), $command, $data]); // (['php', 'artisan', 'foo:bar', 'json data'])

 $process->setoptions(['create_new_console' => true]); //Run process in background 
 $process->start();
}
Enter fullscreen mode Exit fullscreen mode

Just call the above function in your regular PHP code flow and we can achieve asynchronous kind of functionality with this approach.

Tip: Use a table to track process failure.

Top comments (0)