P粉4642089372023-08-18 00:22:33
What you need is to be called a Service Subscriber
In Symfony, when controllers inherit AbstractController
, they are service subscribers, which means they are injected with a library containing some common services (such as twig, serializers, form builders, etc. ) small container.
If you want some "common" services that your child controllers will use, you can extend the list by overriding getSubscribedServices()
in the parent controller. Or if your controller does not inherit the default controller provided by Symfony, you just need to implement your own controller:
If your controller is a service (which I guess it already is), Symfony will use setter injection to inject the container into your controller.
The code will look like this:
<?php use Symfony\Contracts\Service\ServiceSubscriberInterface; class ParentController implement ServiceSubscriberInterface { protected ContainerInterface $container; public function setContainer(ContainerInterface) { $this->container = $container; } public static function getSubscribedServices() { // 这是静态的,所以Symfony可以在不实例化控制器的情况下“看到”所需的服务。 // 在这里定义一些常见的服务,一个示例在Symfony的AbstractController中 } } class ChildController extends ParentController { // 使用自定义DI来为子控制器提供服务。 public function indexAction { // 你可以使用$this->container->get(...)来获取服务 } }