I try to inject dependencies in my handler (service) in my project
class App
{
public function __construct()
{
$this->di();
}
public function di() {
$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions([
RegionSql::class => create(App\Connections\MySqlConnection::class),
CreateRegionHandler::class => create(Region\Infrastructure\Persistance\RegionSql::class),
]);
$container = $containerBuilder->build();
return $container;
}
}
My Handler
class CreateRegionHandler
{
private RegionRepository $repository;
public function __construct(RegionRepository $repository)
{
$this->repository = $repository;
}
RegionRepository
- an interface, RegionSQL
is implementation
I trying to run a handler with something like commandBus
$this->commandBus->execute(new CreateRegionCommand('address', 'postal_code', 'country'));
CommandBus
public function execute($command)
{
$handler = $this->resolveHandler($command);
call_user_func_array([$handler, 'handle'], [$command]);
}
private function resolveHandler($command)
{
$handler_class = substr(get_class($command), 0, -7) . 'Handler';
$run = new \ReflectionClass($handler_class);
return $run->newInstance();
}
But i getting an error
Too few arguments to function Region\Application\Command\CreateRegionHandler::__construct(), 0 passed and exactly 1 expected in Region\Application\Command\CreateRegionHandler.php:
How to get $repository
in my CreateRegionHandler
?
I tried CreateRegionHandler::class => autowire(Region\Infrastructure\Persistance\RegionSql::class)
but it doesn't work too.
Thanks