This project demonstrates how to execute service methods asynchronously in a Symfony application by simply marking them with a custom attribute #[Async].
- A PHP attribute
#[Async]is added to service methods that should run asynchronously. - A custom compiler pass scans all services during container compilation.
- For each service with an
#[Async]method, the compiler pass generates a proxy class invar/cache/async_proxies/that implements the service interface. - The proxy intercepts calls to
#[Async]methods and delegates them to a background process via theAsyncRunnerservice. - The
AsyncRunnertriggers a console command (go:boost) in a separate process usingexec()to perform the actual execution of the method.
-
Add the
#[Async]attribute to a service method (like in ArticleCreator), for example:#[Async] public function create(string $title): void
-
Run the Symfony console command:
symfony console app:create-article "Test Article" -
The command should finish immediately while the actual operation runs in the background.
-
Check
var/log/article_async.logto confirm that the method was executed asynchronously after the command completed.
PS: for now we need the service to implement an interface (classname."Interface") for the proxy generation to work.
- The command returns quickly.
- The background process completes after a short delay.
- The log file shows the asynchronous operation execution.