Skip to content

Latest commit

 

History

History
194 lines (143 loc) · 8.08 KB

File metadata and controls

194 lines (143 loc) · 8.08 KB

Yii

Yii Queue


Latest Stable Version Total Downloads Build status Code coverage Mutation testing badge Static analysis type-coverage

An extension for running tasks asynchronously via queues.

Requirements

  • PHP 8.1 - 8.5.
  • PCNTL extension for signal handling (optional, recommended for production use).

Installation

The package could be installed with Composer:

composer require yiisoft/queue

Quick Start

1. Install an adapter

For production use, you should install an adapter package that matches your message broker (AMQP, Kafka, NATS, and others). See the adapter list and follow the adapter-specific documentation for installation and configuration details.

If you don't have an external broker — whether for development, testing, or because you want to design around QueueInterface from day one and add a real broker later — you can run the queue in synchronous mode (the adapter argument is optional). In this mode messages are processed immediately in the same process, so it won't provide true async execution, but the code stays the same when you switch to a real adapter.

2. Prepare a message and handler

Define a message class for the work to be done — a simple value object with typed properties:

use Yiisoft\Queue\Message\Message;

final class DownloadFileMessage extends Message
{
    public const TYPE = 'download-file';

    public function __construct(
        public readonly string $url,
        public readonly string $destinationPath,
    ) {}

    public static function fromData(string $type, mixed $data): static
    {
        if ($type !== self::TYPE) {
            throw new \InvalidArgumentException("Expected type \"" . self::TYPE . "\", got \"$type\".");
        }
        if (!is_array($data)
            || !is_string($data['url'] ?? null)
            || !is_string($data['destinationPath'] ?? null)
        ) {
            throw new \InvalidArgumentException('Invalid data for ' . self::class . '.');
        }
        return new self($data['url'], $data['destinationPath']);
    }

    public function getType(): string
    {
        return self::TYPE;
    }

    public function getData(): array
    {
        return ['url' => $this->url, 'destinationPath' => $this->destinationPath];
    }
}

Then create a handler that processes it:

use Yiisoft\Queue\Message\MessageInterface;
use Yiisoft\Queue\Message\MessageHandlerInterface;

final readonly class RemoteFileHandler implements MessageHandlerInterface
{
    public function __construct(
        private FileDownloader $downloader,
        private FileProcessor $processor,
    ) {}

    public function handle(MessageInterface $message): void
    {
        assert($message instanceof DownloadFileMessage);
        $localPath = $this->downloader->download($message->url, $message->destinationPath);
        $this->processor->process($localPath);
    }
}

3. Configure the queue

Configuration with yiisoft/config

If you use yiisoft/app or yiisoft/app-api

Add queue configuration to your application $params config. In yiisoft/app/yiisoft/app-api templates it's typically the config/params.php file. If your project structure differs, put it into any params config file that is loaded by yiisoft/config.

Minimal configuration example:

return [
    'yiisoft/queue' => [
        'handlers' => [
            DownloadFileMessage::TYPE => RemoteFileHandler::class,
        ],
    ],
];

Advanced configuration with yiisoft/config

Manual configuration

For setting up all classes manually, see the Manual configuration guide.

4. Send (produce/push) a message to a queue

To send a message to the queue, get the queue instance and call push(). Typically the queue is injected as a dependency:

final readonly class Foo
{
    public function __construct(private QueueInterface $queue) {}

    public function bar(): void
    {
        $this->queue->push(new DownloadFileMessage(
            url: 'https://example.com/file-path.csv',
            destinationPath: '/tmp/file-path.csv',
        ));
    }
}

5. Handle queued messages

By default, Yii Framework uses yiisoft/yii-console to run CLI commands. If you installed yiisoft/app or yiisoft/app-api, you can run the queue worker with one of these two commands:

./yii queue:run # Handle all existing messages in the queue
./yii queue:listen [queueName] # Start a daemon listening for new messages permanently from the specified queue
./yii queue:listen-all [queueName [queueName2 [...]]] # Start a daemon listening for new messages permanently from all queues or specified list of queues (use with caution in production, recommended for dev only)

See Console commands for more details.

In case you're running the queue in synchronous mode (no adapter), queue:listen logs an info message and exits. The messages are processed immediately when pushed.

Documentation

If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.

License

The Yii Queue is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack