首页 > 解决方案 > 如何启动具有依赖关系的服务而不在方法参数中声明它?

问题描述

再会。我想在控制器方法中运行一个名称来自参数的类。该类存在,继承了所需的接口,并通过 new 完美创建。

public function indexAction ($class) {
    if (
        ! empty ($class)
        && class_exists ($class)
        && in_array (DirectPerformerInterface::class, class_implements ($class))
    ) {
        /** @var DirectPerformerInterface $obj */
        $obj = new $class;
        $response = $obj->run();
    }
}

一切正常。但是在构造函数中,被启动的类可能有依赖关系。因此,对于 new,它们必须显式传递(并且类可能不同)或尝试以某种方式通过依赖项运行它。理论上,控制器应该已经受够了:

        /** @var DirectPerformerInterface $obj */
        $obj = $this->get($class);

但是,我有一个错误:

Service "class name" not found: even though it exists in the app's container, the container inside "***\Controller\DirectPerformerController" is a smaller service locator that only knows about the "doctrine", "form.factory", " http_kernel "," parameter_bag "," request_stack "," router "," security.authorization_checker "," security.csrf.token_manager "," security.token_storage "," serializer "," session "," templating "and" twig " services. Try using dependency injection instead.

如果$obj = $this->container->get($class); 文档没有给出正确的答案(可能是因为我无法提出正确的问题),则相同。

请帮我

标签: phpsymfonysymfony4

解决方案


推荐阅读