PHPackages                             romanfedorskij/message-bus - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Queues &amp; Workers](/categories/queues)
4. /
5. romanfedorskij/message-bus

ActiveLibrary[Queues &amp; Workers](/categories/queues)

romanfedorskij/message-bus
==========================

A message handler with interceptor capabilities

3.1.0(1mo ago)023412MITPHPPHP ^7.4 | 8.\*

Since Jan 12Pushed 1mo agoCompare

[ Source](https://github.com/wolfcharaa/message-bus)[ Packagist](https://packagist.org/packages/romanfedorskij/message-bus)[ RSS](/packages/romanfedorskij-message-bus/feed)WikiDiscussions master Synced 1w ago

READMEChangelogDependencies (14)Versions (14)Used By (2)

MessageBus
==========

[](#messagebus)

Lightweight PHP message bus with handler registry, middleware pipeline, event subscribers, message envelopes, headers, and optional queue dispatching.

The library is intended for applications that keep business actions behind small command, query, and event messages, while still needing per-message middleware and lazy handler construction through a PSR container.

This project follows an idea inspired by [vudaltsov](https://github.com/vudaltsov), who laid the conceptual foundation for this style of message bus design.

Requirements
------------

[](#requirements)

- PHP `^7.4 | 8.*`
- `psr/container`
- `psr/clock`
- `psr/log`
- `ext-json`

Installation
------------

[](#installation)

```
composer require romanfedorskij/message-bus
```

Messages
--------

[](#messages)

Messages are plain PHP objects. A message may implement `Message`, `Command`, `Query`, or `Event`, but ordinary objects are also supported.

```
use Wolfcharaa\MessageBus\Message\Command;

final class CreateUserMessage implements Command
{
    public string $email;

    public function __construct(string $email)
    {
        $this->email = $email;
    }
}
```

Handlers
--------

[](#handlers)

Handlers can be invokable classes or callable methods. The callable receives the message and the current context.

```
use Wolfcharaa\MessageBus\Message\Context;

final class CreateUserAction
{
    public function __invoke(CreateUserMessage $message, Context $context): int
    {
        return 123;
    }
}
```

Registry
--------

[](#registry)

Register message definitions with their handlers. `LazyHandlerRegistry` builds handlers only when a message is dispatched.

```
use Wolfcharaa\MessageBus\Builder\Builder;
use Wolfcharaa\MessageBus\HandlerRegistry\LazyHandlerRegistry;
use Wolfcharaa\MessageBus\HandlerRegistry\MessageDefinition;

$registry = new LazyHandlerRegistry(
    new Builder($container),
    [],
    (new MessageDefinition(CreateUserMessage::class))
        ->setHandlerFactory([CreateUserAction::class])
);
```

Dispatch
--------

[](#dispatch)

```
use Wolfcharaa\MessageBus\MessageBus;

$bus = new MessageBus($registry, null, null);

$userId = $bus->dispatch(new CreateUserMessage('user@example.com'));
```

Nested dispatches are available through `Context`; causation and correlation ids are propagated automatically.

```
final class CreateUserAction
{
    public function __invoke(CreateUserMessage $message, Context $context): int
    {
        $context->dispatch(new UserCreatedEvent($message->email));

        return 123;
    }
}
```

Events
------

[](#events)

Events may have multiple subscribers. Middleware is applied once around the whole event dispatch, not once per subscriber.

```
use Wolfcharaa\MessageBus\Message\Event;

final class UserCreatedEvent implements Event
{
    public string $email;

    public function __construct(string $email)
    {
        $this->email = $email;
    }
}

$definition = (new MessageDefinition(UserCreatedEvent::class))
    ->setIsEvent(true)
    ->setHandlerFactory([SendWelcomeEmailAction::class])
    ->setHandlerFactory([WriteAuditLogAction::class]);
```

Headers
-------

[](#headers)

Headers carry metadata alongside the message envelope.

```
use Wolfcharaa\MessageBus\Header;
use Wolfcharaa\MessageBus\PublishOptions;

final class RequestHeader implements JsonSerializable
{
    public string $requestId;

    public function __construct(string $requestId)
    {
        $this->requestId = $requestId;
    }

    public function jsonSerialize(): array
    {
        return get_object_vars($this);
    }
}

$bus->dispatch(
    new CreateUserMessage('user@example.com'),
    new PublishOptions(null, new Header(new RequestHeader('request-1')))
);
```

Default headers can be attached to a message definition:

```
(new MessageDefinition(CreateUserMessage::class))
    ->setDefaultHeader(new Header(new RequestHeader('default-request')))
    ->setHandlerFactory([CreateUserAction::class]);
```

Runtime headers override default headers of the same class.

Queue Dispatch
--------------

[](#queue-dispatch)

Queue support is intentionally transport-agnostic. The library provides:

- `QueueProviderInterface` for application-specific enqueue logic.
- `QueueMiddleware` for intercepting queued messages.
- `QueueHeader` for marking whether the message is being enqueued or already executed by a worker.

Register the middleware globally or for selected messages:

```
use Wolfcharaa\MessageBus\Middleware\QueueMiddleware;

$registry = new LazyHandlerRegistry(
    new Builder($container),
    [QueueMiddleware::class],
    (new MessageDefinition(CreateUserMessage::class))
        ->setShouldQueue()
        ->setHandlerFactory([CreateUserAction::class])
);
```

Implement a provider in the application:

```
use Wolfcharaa\MessageBus\Envelope;
use Wolfcharaa\MessageBus\Queue\QueueProviderInterface;

final class DatabaseQueueProvider implements QueueProviderInterface
{
    public function enqueue(Envelope $envelope): void
    {
        $payload = json_encode($envelope, JSON_THROW_ON_ERROR);

        // Save $payload to the application queue storage.
    }
}
```

When `setShouldQueue()` is enabled, `MessageBus` adds `QueueHeader(false)` to the envelope. `QueueMiddleware` sees the header, sends the envelope to `QueueProviderInterface`, and stops synchronous execution.

Worker Execution
----------------

[](#worker-execution)

The worker should restore the message and dispatch it with `QueueHeader::started()`. This tells `QueueMiddleware` that the job is already running in a worker and must continue to the real handler.

```
use Wolfcharaa\MessageBus\Envelope;
use Wolfcharaa\MessageBus\Header;
use Wolfcharaa\MessageBus\Queue\QueueHeader;

$data = json_decode($payload, true, 512, JSON_THROW_ON_ERROR);
$envelope = Envelope::restore(
    $data,
    new Header(QueueHeader::started())
);

$bus->dispatchEnvelope($envelope);
```

If the application has custom headers, reconstruct them in the `Header` object passed to `Envelope::restore()`.

For queued events, only one queue job is created. In the worker, all event subscribers are executed.

Middleware
----------

[](#middleware)

Middleware receives the current `Context` and `Pipeline`.

```
use Wolfcharaa\MessageBus\Message\Context;
use Wolfcharaa\MessageBus\Middleware\Middleware;
use Wolfcharaa\MessageBus\Pipeline\Pipeline;

final class TransactionMiddleware implements Middleware
{
    public function handle(Context $context, Pipeline $pipeline)
    {
        // begin transaction

        try {
            $result = $pipeline->continue();
            // commit transaction

            return $result;
        } catch (Throwable $e) {
            // rollback transaction
            throw $e;
        }
    }
}
```

Testing
-------

[](#testing)

```
composer test
```

The test suite covers:

- Header replacement and merging.
- Queue middleware enqueue/continue behavior.
- Queued event behavior for both lazy and array registries.

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance92

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 84.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~16 days

Recently: every ~23 days

Total

12

Last Release

41d ago

Major Versions

v0.1.0 → v1.0.02026-01-29

v1.1.0 → v2.0.02026-03-31

2.2.2 → v3.0.02026-07-05

PHP version history (3 changes)0.1.0.x-devPHP &gt;=8.1

v1.0.0PHP ^7.4

v2.0.0PHP ^7.4 | 8.\*

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/110248641?v=4)[Roman Fedorskij](/maintainers/wolfcharaa)[@wolfcharaa](https://github.com/wolfcharaa)

---

Top Contributors

[![wolfcharaa](https://avatars.githubusercontent.com/u/110248641?v=4)](https://github.com/wolfcharaa "wolfcharaa (16 commits)")[![Gaimeboss](https://avatars.githubusercontent.com/u/22555872?v=4)](https://github.com/Gaimeboss "Gaimeboss (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/romanfedorskij-message-bus/health.svg)

```
[![Health](https://phpackages.com/badges/romanfedorskij-message-bus/health.svg)](https://phpackages.com/packages/romanfedorskij-message-bus)
```

###  Alternatives

[symfony/symfony

The Symfony PHP framework

31.4k87.4M2.2k](/packages/symfony-symfony)[tempest/framework

The PHP framework that gets out of your way.

2.3k37.6k21](/packages/tempest-framework)[ecotone/ecotone

Enterprise architecture layer for Laravel and Symfony — CQRS, Event Sourcing, Durable Workflows (Sagas, Orchestrators), Projections, and Outbox messaging via PHP attributes.

568591.1k63](/packages/ecotone-ecotone)[laravel/framework

The Laravel Framework.

34.9k556.2M21.5k](/packages/laravel-framework)[mcp/sdk

Model Context Protocol SDK for Client and Server applications in PHP

1.6k2.2M145](/packages/mcp-sdk)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

86337.5k](/packages/flow-php-flow)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
