You've already forked Php-Template
feat: implement command bus with attribute-based handler resolution and add example command and handler (#27)
All checks were successful
🧪✨ Tests Workflow / 📝 ✨ Code Lint (push) Successful in 1m13s
🧪✨ Tests Workflow / 🛡️ 🔒 Library Audit (push) Successful in 1m24s
🧪✨ Tests Workflow / 🛡️ 🔒 License Check (push) Successful in 1m58s
🧪✨ Tests Workflow / 🧪 ✨ Database Migrations (push) Successful in 2m20s
🧪✨ Tests Workflow / 🐙 🔍 Code Sniffer (push) Successful in 2m5s
🧪✨ Tests Workflow / 🧪 ✅ Unit Tests (push) Successful in 1m0s
All checks were successful
🧪✨ Tests Workflow / 📝 ✨ Code Lint (push) Successful in 1m13s
🧪✨ Tests Workflow / 🛡️ 🔒 Library Audit (push) Successful in 1m24s
🧪✨ Tests Workflow / 🛡️ 🔒 License Check (push) Successful in 1m58s
🧪✨ Tests Workflow / 🧪 ✨ Database Migrations (push) Successful in 2m20s
🧪✨ Tests Workflow / 🐙 🔍 Code Sniffer (push) Successful in 2m5s
🧪✨ Tests Workflow / 🧪 ✅ Unit Tests (push) Successful in 1m0s
Reviewed-on: #27 Co-authored-by: Ron Rise <ron@siteworxpro.com> Co-committed-by: Ron Rise <ron@siteworxpro.com>
This commit was merged in pull request #27.
This commit is contained in:
49
src/CommandBus/AttributeLocator.php
Normal file
49
src/CommandBus/AttributeLocator.php
Normal file
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Siteworxpro\App\CommandBus;
|
||||
|
||||
use League\Tactician\Exception\CanNotInvokeHandlerException;
|
||||
use League\Tactician\Handler\Locator\HandlerLocator;
|
||||
use Siteworxpro\App\Attributes\CommandBus\HandlesCommand;
|
||||
|
||||
class AttributeLocator implements HandlerLocator
|
||||
{
|
||||
private const string HANDLER_NAMESPACE = 'Siteworxpro\\App\\CommandBus\\Handlers\\';
|
||||
|
||||
private array $handlers;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$directory = __DIR__ . '/Handlers';
|
||||
$files = scandir($directory);
|
||||
foreach ($files as $file) {
|
||||
if (pathinfo($file, PATHINFO_EXTENSION) === 'php') {
|
||||
$className = pathinfo($file, PATHINFO_FILENAME);
|
||||
$fullClassName = self::HANDLER_NAMESPACE . $className;
|
||||
|
||||
if (class_exists($fullClassName)) {
|
||||
$reflectionClass = new \ReflectionClass($fullClassName);
|
||||
$attributes = $reflectionClass->getAttributes(HandlesCommand::class);
|
||||
|
||||
foreach ($attributes as $attribute) {
|
||||
$instance = $attribute->newInstance();
|
||||
$commandClass = $instance->commandClass;
|
||||
$this->handlers[$commandClass] = $fullClassName;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getHandlerForCommand($commandName)
|
||||
{
|
||||
if (isset($this->handlers[$commandName])) {
|
||||
$handlerClass = $this->handlers[$commandName];
|
||||
return new $handlerClass();
|
||||
}
|
||||
|
||||
throw new CanNotInvokeHandlerException("No handler found for command: " . $commandName);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user