Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/code-conventions.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@ use Other\SomeOtherB;
- Follows PHPStan level max
- Exclude / ignore rules are discussed per case/topic

## PHP 7.x forward compatibility

- Intended object values are type hinted (`@param object $value` and `@return object`)

## Unit tests

- All of the above, _in general_, applies to unit tests as well
3 changes: 2 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

# News

- **`2018-01-26`** Added initial event sourcing chapter
- **`2018-01-xx`** Added initial _message driven_ chapter
- **`2018-01-26`** Added initial _event sourcing_ chapter
- **`2018-01-25`** Added initial project [code conventions](code-conventions.md)
- **`2018-01-18`** Initial documentation setup. Work in progress as of today.
91 changes: 91 additions & 0 deletions docs/message-driven/cqrs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# Command Query Responsibility Segregation

Command domain objects are provided per domain layer and usually follow a [POPO](https://stackoverflow.com/questions/41188002/what-does-the-term-plain-old-php-object-popo-exactly-mean)
design. It's a specific message type that can be dispatched using any [message bus](domain-message-bus.md).

## Command handlers

A command message is handled by a _command handler_. It's designed, but not limited, to handle one specific command
message.

## Implementations

### `MsgPhp\Domain\Command\EventSourcingCommandHandlerTrait`

Sources a [domain event](../event-sourcing/domain-events.md) from a command message.

- `doHandle($command, callable $onHandled = null): void`
- Invokes the domain event
- If the domain event is handled `$onHandled`, if given, is invoked receiving the handler as first argument
- `abstract getDomainEvent(object $message): DomainEventInterface`
- Get the domain event to be handled
- `abstract getDomainEventHandler($message)`
- Get the [domain event handler](../event-sourcing/domain-event-handlers.md) (should be type
`DomainEventHandlerInterface`)

## Generic example

```php
<?php

class MyCommand { }
class MyCommandHandler
{
public function handle(MyCommand $command): void
{
// do something
}
}

$bus->dispatch(new MyCommand());
```

## Event sourcing example

```php
<?php

use MsgPhp\Domain\Command\EventSourcingCommandHandlerTrait;
use MsgPhp\Domain\Event\{DomainEventHandlerInterface, DomainEventInterface};

class MyCommand { }
class MyCommandHandler
{
use EventSourcingCommandHandlerTrait;

public function handle(MyCommand $command): void
{
$this->doHandle($command, function (MyEntity $entity): void {
// do something, e.g. save entity using a repository
});
}

protected function getDomainEvent(MyCommand $command): DomainEventInterface
{
return new MyDomainEvent();
}

protected function getDomainEventHandler(MyCommand $command)
{
// usually the command provides e.g. an entity identity to be looked up by a repository
return new MyEntity();
}
}

class MyDomainEvent implements DomainEventInterface { }
class MyEntity implements DomainEventHandlerInterface
{
public function handleEvent(DomainEventInterface $event): bool
{
if ($event instanceof MyDomainEvent) {
// do something

return true;
}

return false;
}
}

$bus->dispatch(new MyCommand());
```
16 changes: 16 additions & 0 deletions docs/message-driven/domain-message-bus.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Domain message bus

A domain message bus is bound to `MsgPhp\Domain\DomainMessageBusInterface`. Its purpose is to dispatch any type of
message object and helps you to use CQRS and event sourcing.

## Implementations

- `MsgPhp\Domain\Infra\SimpleBus\DomainMessageBus`
- Dispatches both _command_ and _event_ message types
- Requires `simple-bus/message-bus`

## API

### `dispatch(object $message): mixed`

Dispatches the given message object. The bus can return a value coming from handlers, but is not required to do so.
3 changes: 3 additions & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,6 @@ pages:
- Event sourcing:
- Domain events: event-sourcing/domain-events.md
- Domain event handlers: event-sourcing/domain-event-handlers.md
- Message driven:
- Domain message bus: message-driven/domain-message-bus.md
- CQRS: message-driven/cqrs.md
3 changes: 3 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ parameters:
# see https://github.com/sebastianbergmann/phpunit/pull/2963
- '#Parameter \#1 \$originalClassName of method PHPUnit\\Framework\\TestCase::createMock\(\) expects string, array<int, string> given\.#'

# see https://github.com/symfony/symfony/pull/25644
- '#Strict comparison using === between null and string will always evaluate to false\.#'

# fluent mixed interface usage in src/*Bundle/DependencyInjection/Configuration.php
- '#Call to an undefined method Symfony\\Component\\Config\\Definition\\Builder\\NodeDefinition::append\(\)\.#'

Expand Down
40 changes: 40 additions & 0 deletions src/Domain/Command/EventSourcingCommandHandlerTrait.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace MsgPhp\Domain\Command;

use MsgPhp\Domain\Event\{DomainEventInterface, DomainEventHandlerInterface};

/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
trait EventSourcingCommandHandlerTrait
{
/**
* @param object $command
*/
protected function doHandle($command, callable $onHandled = null): void
{
$event = $this->getDomainEvent($command);
$handler = $this->getDomainEventHandler($command);

if (!$handler instanceof DomainEventHandlerInterface) {
throw new \LogicException(sprintf('Object "%s" is unable to handle domain event "%s". Did you forgot to implement DomainEventHandlerInterface?', get_class($handler), get_class($event)));
}

if ($handler->handleEvent($event) && null !== $onHandled) {
$onHandled($handler);
}
}

/**
* @param object $command
*/
abstract protected function getDomainEvent($command): DomainEventInterface;

/**
* @param object $command
*/
abstract protected function getDomainEventHandler($command): DomainEventHandlerInterface;
}
16 changes: 16 additions & 0 deletions src/Domain/DomainMessageBusInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace MsgPhp\Domain;

/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
interface DomainMessageBusInterface
{
/**
* @param object $message
*/
public function dispatch($message);
}
65 changes: 54 additions & 11 deletions src/Domain/Infra/DependencyInjection/Bundle/ConfigHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace MsgPhp\Domain\Infra\DependencyInjection\Bundle;

use MsgPhp\Domain\DomainId;
use MsgPhp\Domain\Event\DomainEventHandlerInterface;
use MsgPhp\Domain\Infra\Uuid as UuidInfra;
use Ramsey\Uuid\UuidInterface;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
Expand All @@ -21,30 +22,31 @@ final class ConfigHelper
public const NATIVE_DATA_TYPES = ['string', 'integer', 'bigint'];
public const UUID_DATA_TYPES = ['uuid', 'uuid_binary', 'uuid_binary_ordered_time'];

public static function createClassMappingNode(string $name, array $required = [], \Closure $normalizer = null, $defaultValue = null, NodeBuilder $builder = null): ArrayNodeDefinition
public static function createClassMappingNode(string $name, array $required = [], \Closure $normalizer = null, $defaultValue = null, string $prototype = 'scalar', \Closure $prototypeCallback = null, NodeBuilder $builder = null): ArrayNodeDefinition
{
$node = ($builder ?? new NodeBuilder())->arrayNode($name);
$node->useAttributeAsKey('class');

if ($required) {
$node->isRequired();

foreach ($required as $class) {
$node->validate()
->ifTrue(function (array $value) use ($class) {
return !isset($value[$class]);
})
->thenInvalid(sprintf('Class "%s" must be configured.', $class))
->end();
$node->validate()->ifTrue(function (array $value) use ($class) {
return !isset($value[$class]);
})->thenInvalid(sprintf('Class "%s" must be configured.', $class));
}
}

if ($normalizer) {
if (null !== $normalizer) {
$node->beforeNormalization()->always($normalizer);
}

$node
->useAttributeAsKey('class')
->scalarPrototype()->defaultValue($defaultValue)->end();
$prototype = $node->prototype($prototype);
$prototype->defaultValue($defaultValue);

if (null !== $prototypeCallback) {
$prototypeCallback($prototype);
}

return $node;
}
Expand Down Expand Up @@ -98,6 +100,47 @@ public static function resolveClassMapping(array $dataTypeMap, array $dataTypeMa
unset($value, $config);
}

public static function resolveCommandMapping(array $classMapping, array $mapping, array &$config): void
{
foreach ($mapping as $class => $traits) {
$mappedClass = $classMapping[$class] ?? $class;
if ($class !== $mappedClass && !is_subclass_of($mappedClass, $class)) {
continue;
}

$isEventHandler = is_subclass_of($mappedClass, DomainEventHandlerInterface::class);
foreach ($traits as $trait => $traitConfig) {
if (!self::uses($mappedClass, $trait)) {
continue;
}

$config += array_fill_keys($traitConfig, $isEventHandler);
}
}
}

private static function uses(string $class, string $trait): bool
{
static $uses = [];

if (!isset($uses[$class])) {
$resolve = function (string $class) use (&$resolve): array {
$resolved = [];

foreach (class_uses($class) as $used) {
$resolved[$used] = true;
$resolved += $resolve($used);
}

return $resolved;
};

$uses[$class] = $resolve($class);
}

return isset($uses[$class][$trait]);
}

private function __construct()
{
}
Expand Down
Loading