DEV Community

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

Posted on

5 3

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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay