PHP7 中的 MessageBus (CommandBus、EventBus 和 QueryBus) 实现
Implementation for the CommandBus, the QueryBus and the EventBus in PHP 7 and using PSR-11.
Use Composer to install the package:
$ composer require nilportugues/messagebusThe idea of a message bus is that you create message objects that represent what you want your application to do. Then, you toss it into the bus and the bus makes sure that the message object gets to where it needs to go.
Easy right? Keep reading!
A Message Bus is a pipe of Messages. This implementation takes care of 3 types of messages, Commands, Queries and Events. While all look similar at first, their intent is different.
From this classification, one can spot that Command and Events can work together very well.
Given the nature of the message, implementing an interface, you may write behaviours that wrap the message to log, process or modify the response using the Decorator pattern. These are called Middleware.
For instance:
To wrap-up, its benefits are:
username = $username;
$this->password = $password;
$this->emailAddress = $emailAddress;
}
//getters...
}The Command Handler must implement the CommandHandler interface and implement the __invoke method.
For instance:
userRepository = $userRepository;
}
public function __invoke(RegisterUser $command)
{
$user = new User(
$command->getUsername(),
$command->getPassword(),
$command->getEmail(),
);
$this->userRepository->save($user);
}
}I'm assuming you're using some kind Service Container. Now it's time to register your CommandHandler.
For instance, in a Psr\Container compliant Service Container, we can do this as follows:
get('UserRepository');
};The Command Bus Middleware requires two classes to be injected. First one is the command translator, and second one the handler resolver.
CommandTranslator
Classes implementing this interface will provide the FQN for the Handler class given a Command.
This package provides an implementation, NilPortugues\MessageBus\CommandBus\Translator\AppendStrategy which basically appends the word Handler to the provided Command class.
For custom strategies, you may write your own implementing the NilPortugues\MessageBus\CommandBus\Contracts\CommandTranslator interface.
CommandHandlerResolver
Classes implementing this interface will be resolving the class for the instance required based on the output of the CommandTranslator used.
This package provides an implementation, NilPortugues\MessageBus\CommandBus\Resolver\PsrContainerResolver, that expects any Service Container implementing the Psr\Container interface.
For Symfony 2 and 3 framework users up to version 3.2, you should use Symfony Container: NilPortugues\MessageBus\CommandBus\Resolver\SymfonyContainerResolver. For Symfony 3.3 and up use the PSR-11 ContainerResolver class.
The minimum set up to get the Command Bus working is:
get('CommandTranslator'),
$container->get('CommandHandlerResolver'),
);
};
$container['CommandBus'] = function($container) {
return new \NilPortugues\MessageBus\CommandBus\CommandBus([
$container->get('CommandBusMiddleware'),
]);
};If for instance, we want to log everything happening in the Command Bus, we'll add to the middleware list the logger middleware. This will wrap the Command Bus, being able to log before and after it ran, and if there was an error.
get('Monolog')
);
};
//Update the CommandBus with the LoggerCommandBusMiddleware
$container['CommandBus'] = function($container) {
return new \NilPortugues\MessageBus\CommandBus\CommandBus([
$container->get('LoggerCommandBusMiddleware'),
$container->get('CommandBusMiddleware'),
]);
};Finally, to make use of the CommandBus, all you need to do is run this code:
get('CommandBus');
$command = new RegisterUser('MyUsername', 'MySecretPassword', '[email protected]');
$commandBus($command);TransactionalCommandBusMiddleware
NilPortugues\MessageBus\CommandBus\TransactionalCommandBusMiddlewarebeginTransaction-commit and rollback if any kind of exception is thrown.LoggerQueryBusMiddleware
NilPortugues\MessageBus\CommandBus\LoggerCommandBusMiddlewareIn order to write custom middleware a new class implementing the NilPortugues\MessageBus\CommandBus\Contracts\CommandBusMiddleware interface is required.
userId = $userId;
}
public function getUserId() : string
{
return $this->userId;
}
}The Query Handler must implement the QueryHandler interface and implement the __invoke method.
For instance:
userRepository = $userRepository;
}
public function __invoke(GetUser $query) : QueryResponse
{
$userId = $query->getUserId();
$user = $this->userRepository->find($userId);
return new UserQueryResponse($user);
}
}Response queries are generic responses.
If you take into account section 2.1.2, you'll see the UserQueryResponse has a $user injected into the constructor. This has been done in order to reuse the QueryResponse in other scenarios such as fetching an updated user.
get('UserRepository'));
};The Query Bus Middleware requires two classes to be injected. First one is the query translator, and second one the handler resolver.
QueryTranslator
Classes implementing this interface will provide the FQN for the Handler class given a Query.
This package provides an implementation, NilPortugues\MessageBus\QueryBus\Translator\AppendStrategy which basically appends the word Handler to the provided Query class.
For custom strategies, you may write your own implementing the NilPortugues\MessageBus\QueryBus\Contracts\QueryTranslator interface.
QueryHandlerResolver
Classes implementing this interface will be resolving the class for the instance required based on the output of the QueryTranslator used.
This package provides an implementation, NilPortugues\MessageBus\QueryBus\Resolver\PsrContainerResolver, that expects any Service Container implementing the Psr\Container interface.
For Symfony 2 and 3 framework users up to version 3.2, you should use Symfony Container: NilPortugues\MessageBus\QueryBus\Resolver\SymfonyContainerResolver. For Symfony 3.3 and up use the PSR-11 ContainerResolver class.
The minimum set up to get the Query Bus working is:
get('QueryTranslator'),
$container->get('QueryHandlerResolver'),
);
};
$container['QueryBus'] = function($container) {
return new \NilPortugues\MessageBus\QueryBus\QueryBus([
$container->get('QueryBusMiddleware'),
]);
};If for instance, we want to log everything happening in the Query Bus, we'll add to the middleware list the logger middleware. This will wrap the Query Bus, being able to log before and aft
暂无开放 Issues,或尚未同步最近议题。