PHPackages                             itantik/cq-dispatcher - 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. [CLI &amp; Console](/categories/cli)
4. /
5. itantik/cq-dispatcher

ActiveLibrary[CLI &amp; Console](/categories/cli)

itantik/cq-dispatcher
=====================

Command Query Dispatcher with middleware support.

v0.5.1(5y ago)0131MITPHPPHP &gt;= 7.2

Since May 24Pushed 5y ago1 watchersCompare

[ Source](https://github.com/itantik/cq-dispatcher)[ Packagist](https://packagist.org/packages/itantik/cq-dispatcher)[ RSS](/packages/itantik-cq-dispatcher/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (8)Versions (3)Used By (1)

CQ Dispatcher
=============

[](#cq-dispatcher)

Command Query Dispatcher with middleware support. This library can have its place in applications that are designed according to the principles of *Command Query Separation* (CQS) or *Command Query Responsibility Segregation* (CQRS).

CQ Dispatcher is typically located in the *application service layer*, its clients are controllers and presenters from *UI layer*. It dispatches application requests, these are commands and queries, finds an appropriate handler and executes it.

**Command** represents a request, that performs an action through a command handler. It **modifies** data or changes the state of objects. It **doesn't return** a value.

**Query** represents a request, that gets a data through a query handler. It **must not modify** data. It **returns** a value.

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

[](#installation)

```
composer require itantik/cq-dispatcher

```

Usage
-----

[](#usage)

CQ Dispatcher requires a dependency injection container. You have to define an adapter to your DI container. Adapter implements `Itantik\CQDispatcher\DI\IContainer`.

#### Usage with Nette framework

[](#usage-with-nette-framework)

Install [itantik/nette-cq-dispatcher](https://github.com/itantik/nette-cq-dispatcher) extension for [Nette framework](https://nette.org/). It is configured to use Nette DI Container.

### Example of file structure

[](#example-of-file-structure)

Assume that the application service layer has the following file structure:

```
- UserService
    - UserCommands.php  // command dispatcher
    - UserQueries.php   // query dispatcher
    - Command
        - AddUserCommand.php
        - AddUserHandler.php
        - ChangePasswordCommand.php
        - ChangePasswordHandler.php
        - ... // other commands/handlers
    - Query
        - FindAllUsersQuery.php
        - FindAllUsersHandler.php
        - GetUserQuery.php
        - GetUserHandler.php
        - ... // other queries/handlers
- Middleware
    - TransactionalMiddleware.php

```

### Command

[](#command)

Command is a plain object that implements `Itantik\Middleware\IRequest` interface and class name uses optional `Command` suffix. The command object represents your request.

```
class AddUserCommand implements IRequest
{
    /** @var int */
    private $id;
    /** @var string */
    private $name;
    /** @var string */
    private $surname;

    public function __construct(int $id, string $name, string $surname)
    {
        $this->id = $id;
        $this->name = $name;
        $this->surname = $surname;
    }

    public function id(): int
    {
        return $this->id;
    }

    public function name(): string
    {
        return $this->name;
    }

    public function surname(): string
    {
        return $this->surname;
    }
}
```

### Command Handler

[](#command-handler)

Command handler implements `Itantik\CQDispatcher\Command\ICommandHandler` interface and class name should use `Handler` suffix. Command handler represents an application service.

```
class AddUserHandler implements ICommandHandler
{
    /** @var UserRepository */
    private $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function handle(AddUserCommand $command): void
    {
        $user = new User($command->id(), $command->name(), $command->surname());
        $this->repository->add($user);
    }
}
```

### Command Dispatcher

[](#command-dispatcher)

Command dispatcher creates an appropriate command handler based on the command class name, then invokes its `handle` method. For each command, there is a single command handler.

By default, pairing command with its handler is based on class names.

Command `Namespace\SomeCommand` uses `Namespace\SomeHandler` handler. `Command` suffix is optional, so you can name command as `Namespace\Some` instead of `Namespace\SomeCommand`.

#### Creating Command Dispatcher

[](#creating-command-dispatcher)

Command dispatcher extends abstract class `\Itantik\CQDispatcher\Commands`.

```
class UserCommands extends \Itantik\CQDispatcher\Commands
{
}
```

#### Using in Controllers and Presenters

[](#using-in-controllers-and-presenters)

```
// simplified code

class UserController
{
    /** @var UserCommands */
    private $userCommands;

    public function actionAddUser(string $name, string $surname): void
    {
        // create a command
        $id = SomeIdGenerator::next();
        $command = new AddUserCommand($id, $name, $surname);
        try {
            // execute command
           $this->userCommands->execute($command);
        } catch (\Exception $ex) {
            // handle error
            // ...
        }
        // redirect to user detail page
        // ...
    }
}
```

#### Extending with Middleware

[](#extending-with-middleware)

Command dispatcher has built-in [itantik/middleware](https://github.com/itantik/middleware) support.

For example, middleware for wrapping each command handler with a database transaction can look like this:

```
final class TransactionalMiddleware implements Itantik\Middleware\IMiddleware
{
    /** @var DatabaseConnection */
    private $connection;

    public function __construct(DatabaseConnection $connection)
    {
        $this->connection = $connection;
    }

    public function handle(IRequest $request, ILayer $nextLayer): IResponse
    {
        $connection = $this->connection;
        $connection->beginTransaction();
        try {
            $res = $nextLayer->handle($request);
            $connection->commit();
            return $res;
        } catch (Exception $e) {
            $connection->rollback();
            throw $e;
        }
    }
}
```

Extending command dispatcher:

```
class UserCommands extends \Itantik\CQDispatcher\Commands
{
    public function __construct(
        ICommandDispatcher $commandDispatcher,
        DatabaseConnection $connection
    ) {
        parent::__construct($commandDispatcher);
        $this->appendMiddleware(new TransactionalMiddleware($connection));
    }
}
```

Using in controller is not changed. Now each command is executed in database transaction.

### Query

[](#query)

Query implements `Itantik\Middleware\IRequest` interface and class name uses optional `Query` suffix.

```
class FindAllUsersQuery implements IRequest
{
}
```

### Query Handler

[](#query-handler)

Query handler implements `Itantik\CQDispatcher\Query\IQueryHandler` interface, class name should use `Handler` suffix, `handle` method returns a value.

```
class FindAllUsersHandler implements IQueryHandler
{
    /** @var UserRepository */
    private $repository;

    public function __construct(UserRepository $repository)
    {
        $this->repository = $repository;
    }

    public function handle(FindAllUsersQuery $query): UserList
    {
        return $this->repository->findAll();
    }
}
```

### Query Dispatcher

[](#query-dispatcher)

Similar to the command dispatcher.

Query `Namespace\SomeQuery` uses `Namespace\SomeHandler` handler. `Query` suffix is optional, so you can name query as `Namespace\Some` instead of `Namespace\SomeQuery`.

#### Creating Query Dispatcher

[](#creating-query-dispatcher)

Query dispatcher extends abstract class `\Itantik\CQDispatcher\Queries`.

```
class UserQueries extends \Itantik\CQDispatcher\Queries
{
}
```

#### Using in Controllers and Presenters

[](#using-in-controllers-and-presenters-1)

```
// simplified code

class UserController
{
    /** @var UserQueries */
    private $userQueries;

    public function actionAllUsers(): void
    {
        // create a query
        $query = new FindAllUsersQuery();
        // execute query
       $userList = $this->userQueries->execute($query);

        // fill-in template
        // ...
    }
}
```

#### Extending with Middleware

[](#extending-with-middleware-1)

The same as with the Command dispatcher.

Requirements
============

[](#requirements)

- PHP 7.2

###  Health Score

20

—

LowBetter than 14% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity42

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~15 days

Total

2

Last Release

2162d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b1b1f4da26cfd34d5c88f5a5fe1b02b4441a9bb0b0bfb494791968cde4f4079?d=identicon)[itantik](/maintainers/itantik)

---

Top Contributors

[![itantik](https://avatars.githubusercontent.com/u/10348473?v=4)](https://github.com/itantik "itantik (4 commits)")

###  Code Quality

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/itantik-cq-dispatcher/health.svg)

```
[![Health](https://phpackages.com/badges/itantik-cq-dispatcher/health.svg)](https://phpackages.com/packages/itantik-cq-dispatcher)
```

###  Alternatives

[wp-cli/wp-cli

WP-CLI framework

5.0k17.2M319](/packages/wp-cli-wp-cli)[consolidation/annotated-command

Initialize Symfony Console commands from annotated command class methods.

22569.8M18](/packages/consolidation-annotated-command)[chi-teck/drupal-code-generator

Drupal code generator

26947.8M5](/packages/chi-teck-drupal-code-generator)[seld/cli-prompt

Allows you to prompt for user input on the command line, and optionally hide the characters they type

24725.8M17](/packages/seld-cli-prompt)[illuminate/console

The Illuminate Console package.

12944.1M5.1k](/packages/illuminate-console)[php-tui/php-tui

Comprehensive TUI library heavily influenced by Ratatui

589747.0k6](/packages/php-tui-php-tui)

PHPackages © 2026

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