How do I get services (dependencies) in a custom class

前端 未结 5 469
礼貌的吻别
礼貌的吻别 2020-12-29 23:43

In the controller, I could do

$this->get(\'service.name\')

But in a custom class, how can I do that?

相关标签:
5条回答
  • 2020-12-29 23:51

    If you do not know the full list of dependencies that you need at the moment when the service is created, you can pass the container as the argument http://symfony.com/doc/current/book/service_container.html#using-the-expression-language

    services:  
        service_name:  
            class: AppBundle\Class  
            arguments: ['@=container']
    
    0 讨论(0)
  • 2020-12-30 00:00

    Define your custom class as a service, and then inject dependencies into it.

    Ex:

    // services.yml
    services:
       my.custom.service.id:
           class: My\Custom\Class
           arguments:
             - @service.name
             - @doctrine.orm.entity_manager
    

    Your custom class' constructor would then get those services as arguments.

    Be sure to read up on the Service Container in the official docs. It goes over all this in great detail.

    0 讨论(0)
  • 2020-12-30 00:03

    Accessing the service container in a custom class (not in a service defined class)

    This is not best practice to do, but it works. If your custom class is not set to be a service then you can access the service container using global variable $kernel:

    class Helper {
    
        private $container;
    
        /**
         * Constructor assigns service container to private container. 
         */
        public function __construct() {
    
            global $kernel;
            $this->container = $kernel->getContainer();
    
        }
    
        function doSOmething() {
            $someService = $this->container->get('service.name');
            // do something with someService ...
        }
    
    }
    
    0 讨论(0)
  • 2020-12-30 00:04

    You were on the right track with ContainerAware.

    $this->get('id') is actually a shortcut to $this->container->get('id'). And getting container into your class is as simple as implementing ContainerAwareInterface - putting this snippet into your class:

    public function setContainer(\Symfony\Component\DependencyInjection\ContainerInterface $container = null)
    {
        $this->container = $container;
    }
    
    0 讨论(0)
  • 2020-12-30 00:12

    OK I suppose @Arms answer is a possible solution, I found by looking at the source to Controller, I could extend ContainerAware

    0 讨论(0)
提交回复
热议问题