简体   繁体   中英

Symfony _defaults in bundles

I'm a newbie in Symfony and have a few questions about the dependency injection, particularly about Symfony 3.3

  1. Can the new _defaults block be declared for every single bundle separately or it's global and defined in the hosting app?

  2. Can I use the new things like autowiring in my reusable bundles or I have to declare all the bundle's services separately?

  1. It's per file declaration. You can also override it at single service definitions. Eg

    # app/config/services.yml services: _defaults: autowire: true App\\SomeService: autowire: false
  2. In short: yes.

I feel you're asking how to combine all this features together and what is the best practise for it . Saying that, I'll extend my answer with multi-bundle example of service definitions.

Application with 2 Bundles would look like this

imports:
    - { resource: "../../src/FirstBundle/config/services.yml" }
    - { resource: "../../src/SecondBundle/config/services.yml" }

services:
    _defaults:
        autowire: true

    App\SomeService:
        autowire: false

With first bundle:

# src/FirstBundle/config/services.yml

services:
    _defaults:
        autowire: true

    App\FirstBundle\:
        resource: ../..

And second bundle:

# src/SecondBundle/config/services.yml

services:
    _defaults:
        autowire: true

    App\SecondBundle\:
        resource: ../..

One Extra Tip

Also, you can improve first file to just single line import thanks to glob patterns .

I use it in practise like this:

imports:
    - { resource: "../../src/**/config/services.yml" }

services:
    _defaults:
        autowire: true

    App\SomeService:
        autowire: false

You can read more about Symfony 3.3 dependency-injection features in this post with before/after config examples .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM