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
It seems you are creating the Container in the App
class, but you are not using it then.
PHP-DI will not magically intercept class creations. You have to use $container->get(<class name>)
instead of $run->newInstance()
.
See the documentation for more details.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.