Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msankhala/b7d702fbbec431e72ffee6040b618041 to your computer and use it in GitHub Desktop.
Save msankhala/b7d702fbbec431e72ffee6040b618041 to your computer and use it in GitHub Desktop.
symfony dependency injection cheet sheet.

Symfony Service container cheetsheet:

https://symfony.com/doc/current/service_container.html

Passing arguments to service:

services:
  site_update_manager.superadmin:
    class: App\Updates\SiteUpdateManager
    # you CAN still use autowiring: we just want to show what it looks like without
    autowire: false
    # manually wire all arguments
    arguments:
      - '@App\Service\MessageGenerator'
      - '@mailer'
      - 'superadmin@example.com'

Passing parameters:

parameters:
    admin_email: manager@example.com

services:
  site_update_manager.superadmin:
    class: App\Updates\SiteUpdateManager
    arguments:
      $adminEmail: '%admin_email%'

Provide arguments with setter

https://symfony.com/doc/current/service_container/calls.html

services:
    class: App\Service\MessageGenerator:
    # ...
    calls:
        - method: setLogger
          arguments:
              - '@logger'

Provide argument from the result of calling other service/ Inject Values Based on Complex Expressions.

https://symfony.com/doc/current/service_container/expression_language.html

# config/services.yaml
services:
  class: App\Mail\MailerConfiguration: ~

  class: App\Mailer:
    arguments: ["@=service('App\\\\Mail\\\\MailerConfiguration').getMailerMethod()"]

Use factory

http://symfony.com/doc/current/service_container/factories.html

services:
    # ...

    App\Email\NewsletterManagerFactory: ~

    App\Email\NewsletterManager:
        # call a method on the specified factory service
        factory: 'App\Email\NewsletterManagerFactory:createNewsletterManager'

Manage Common Dependencies with Parent Services

https://symfony.com/doc/current/service_container/parent_services.html

How to Configure a Service with a Configurator

https://symfony.com/doc/current/service_container/configurators.html#using-the-configurator

Override a default service

todo?

Multiple Service Definitions Using the Same Namespace

https://symfony.com/doc/current/service_container.html#multiple-service-definitions-using-the-same-namespace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment