我尝试在项目中的处理程序(服务)中注入依赖项
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'));
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();
}但是我得到一个错误的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),但它也不起作用。谢谢
发布于 2020-05-27 18:33:00
看起来您是在App类中创建容器,但您并没有使用它。
PHP-DI不会神奇地拦截类的创建。您必须使用$container->get(<class name>)而不是$run->newInstance()。
有关更多详细信息,请参阅the documentation。
https://stackoverflow.com/questions/62040939
复制相似问题