0

我尝试在我的项目的处理程序(服务)中注入依赖项

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:

如何进入$repository我的CreateRegionHandler?我试过CreateRegionHandler::class => autowire(Region\Infrastructure\Persistance\RegionSql::class)了,但它也不起作用。谢谢

4

1 回答 1

0

似乎您正在App类中创建容器,但那时您没有使用它。

PHP-DI 不会神奇地拦截类的创建。您必须使用$container->get(<class name>)而不是$run->newInstance().

有关更多详细信息,请参阅文档

于 2020-05-27T10:33:00.147 回答