php - 如何启动具有依赖关系的服务而不在方法参数中声明它?
问题描述
再会。我想在控制器方法中运行一个名称来自参数的类。该类存在,继承了所需的接口,并通过 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);
文档没有给出正确的答案(可能是因为我无法提出正确的问题),则相同。
请帮我
解决方案
推荐阅读
- python - 为什么从 cmd 运行 .py 与使用 anaconda 提示符运行时自动换行(QTableWidget、PYQT5)的绘制方式不同?
- html - css3中的元素定位
- sapui5 - ModelContextChange 事件的触发器
- javascript - Firefox 是否支持 SVG getIntersectionList?文档和测试不同意
- python - 更改目录停用 venv
- python - Python:通过 AND & OR 分配的字符串值
- sql - 有查询树的快捷方式吗?
- flutter - 如何使用 just_audio (flutter) 从我的 api 中获取带有受保护 url 的音频
- sorting - 如果其中一个字段小于某个值,如何打印列中的某些字段?
- sql - 如何相交 2 个子查询