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

前端 未结 5 487
礼貌的吻别
礼貌的吻别 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条回答
  •  Happy的楠姐
    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.

提交回复
热议问题