[英]Why PHP definitions in PHP-DI not working?
我尝试在我的项目的处理程序(服务)中注入依赖项
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;
}
}
我的处理程序
class CreateRegionHandler
{
private RegionRepository $repository;
public function __construct(RegionRepository $repository)
{
$this->repository = $repository;
}
RegionRepository
- 一个接口, RegionSQL
是实现
我试图用类似 commandBus 的东西运行一个处理程序
$this->commandBus->execute(new CreateRegionCommand('address', 'postal_code', 'country'));
命令总线
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();
}
但是我收到一个错误Too few arguments to function Region\Application\Command\CreateRegionHandler::__construct(), 0 passed and exactly 1 expected in Region\Application\Command\CreateRegionHandler.php:
如何在我的CreateRegionHandler
中获取$repository
? 我试过CreateRegionHandler::class => autowire(Region\Infrastructure\Persistance\RegionSql::class)
但它也不起作用。 谢谢
看来您正在App
class 中创建容器,但那时您没有使用它。
PHP-DI 不会神奇地拦截 class 创作。 您必须使用$container->get(<class name>)
而不是$run->newInstance()
。
有关更多详细信息,请参阅文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.