問題描述
我有一部分代碼,我通過依賴注入注入了兩個服務 $checker
和 $paginator
.它完美地工作:
I have a part of code where I'm injecting two services $checker
and $paginator
by dependency injection. It works perfectly:
public function index(Request $request, Paginator $paginator, Checker $checker)
{
$result = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
$partialResult = $paginator->getPartial($result, 0, 3);
$checker->isValid('A');
var_dump("test");
die;
}
在services.yaml
文件的配置下面:
paginator:
public: true
class: 'AppHelperPaginator'
checker:
public: true
class: 'AppHelperChecker'
arguments:
$paginator: '@paginator'
但由于某些原因我想通過方法注入服務:
But I'd like to inject for some reasons service by method:
$checker = $this->container->get('checker');
但它不起作用.在以前的 Symfony 版本中,像 3.4 那樣.
But it doesn't work. In previous versions Symfony like 3.4 it used to.
我收到一個錯誤:
未找到服務checker":事件雖然它存在于應用程序的容器中,但AppControllerDefaultController"中的容器是一個較小的服務定位器,它只知道http_kernel"、parameter_bag"、request_stack"、路由器"、會話"和樹枝"服務.嘗試改用依賴注入.
Service "checker" not found: event though it exists in the app's container, the container inside "AppControllerDefaultController" is a smaller service locator that only knows about the "http_kernel", "parameter_bag", "request_stack", "router", "session", and "twig" services. Try using dependency injection instead.
我該如何解決這個問題?
How should I solve this?
推薦答案
你需要添加你的依賴項 服務定位器可以找到它們.
You need to add your dependencies so the service locator can find them.
將方法 getSubscribedServices()
添加到您的控制器類:
Add a method getSubscribedServices()
to your controller class:
public static function getSubscribedServices()
{
return array_merge(
parent::getSubscribedServices(),
[
'checker' => Checker::class,
]
);
}
如果你的控制器類擴展了 AbstractController
你可以簡單地做:
If your controller class extends AbstractController
you can simply do:
$this->get('checker');
如果您想在其他類型的類中執行此操作(例如不擴展AbstractController
的服務),那么您需要聲明您的服務實現了ServiceSubscriberInterface
.
If you want to do it in another type of class (e.g. a service that doesn't extend AbstractController
), then you need to declare that your service implements the ServiceSubscriberInterface
.
use SymfonyContractsServiceServiceSubscriberInterface;
use PsrContainerContainerInterface;
class FooService implements ServiceSubscriberInterface {
public function __construct(ContainerInterface $locator)
{
$this->locator = $locator;
}
public static function getSubscribedServices() { /* same as before */ }
public function get($service)
{
return $this->locator->get($service);
}
}
...并且您可以像之前在控制器中那樣做同樣的事情.
... and you would be able to do the same than you in the controller earlier.
這篇關于如果我沒有/無法使用 DI 注入服務,我如何直接從容器中獲取服務?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!