tourze/symfony-async-bundle

Symfony异步模块

0.0.5 2025-03-28 19:22 UTC

This package is auto-updated.

Last update: 2025-03-29 10:40:31 UTC


README

English | 中文

Latest Version Total Downloads License

A Symfony bundle that provides asynchronous command execution and service method invocation capabilities using Symfony Messenger.

Features

  • Asynchronous command execution with full support for options and arguments
  • Service method invocation through the #[Async] attribute
  • Built-in error handling and logging
  • Automatic retry mechanism for failed operations
  • Delayed execution support
  • Full integration with Symfony Messenger

Requirements

  • PHP 8.1 or higher
  • Symfony 6.4 or higher
  • Symfony Messenger component

Installation

composer require tourze/symfony-async-bundle

Configuration

Enable the bundle in your config/bundles.php:

return [
    // ...
    Tourze\Symfony\Async\AsyncBundle::class => ['all' => true],
];

Make sure you have configured Symfony Messenger with appropriate transport for async messages.

Quick Start

Asynchronous Command Execution

<?php

use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Messenger\Stamp\AsyncStamp;
use Tourze\Symfony\Async\Message\RunCommandMessage;

class MyController
{
    public function __construct(
        private readonly MessageBusInterface $messageBus
    ) {}

    public function someAction()
    {
        // Create a message to run a command asynchronously
        $message = new RunCommandMessage();
        $message->setCommand('app:my-command');
        $message->setOptions([
            '--option1' => 'value1',
            '--option2' => 'value2'
        ]);

        // Dispatch to queue
        $this->messageBus->dispatch($message, [
            new AsyncStamp()
        ]);

        return 'Command queued for execution';
    }
}

Using Async Attribute

You can mark any service method for asynchronous execution using the #[Async] attribute:

<?php

namespace App\Service;

use Tourze\Symfony\Async\Attribute\Async;

class ReportGenerator
{
    #[Async(retryCount: 3, delayMs: 5000)]
    public function generateLargeReport(int $userId): void
    {
        // This method will be executed asynchronously
        // with 3 retry attempts and 5-second delay

        // ...time-consuming operations
    }
}

Then call the method normally:

$reportGenerator->generateLargeReport(123);
// This returns immediately, with the actual work happening in the background

Contributing

Please see CONTRIBUTING.md for details.

License

The MIT License (MIT). Please see License File for more information.