phpsymfonydependency-injectionyamlsymfony-components

Symfony Dependency Injection inject new instance of class


I'm using symfony/dependency-injection component (note: not using the full stack framework)

When registering a new service i want to inject in the constructor a new instance of a class. Example:

$container->register('session', 'Vendor\Core\Session')
    ->addArgument(new PhpBridgeSessionStorage());

The example works very well but what if I want to use yml files for defining this service? Something like:

services:
  session:
    class: Vendor\Core\Session
    arguments: [ new Class\To\Inject ]

Am I forced to define Class\To\Inject as a new service? or create a Service factory?


Solution

  • Scopes have been deprecated since 2.8. Use shared: false instead.

    http://symfony.com/doc/current/cookbook/service_container/shared.html

    services:
      session:
        class: Vendor\Core\Session
        arguments: [ "@inject.me" ]
    
      inject.me:
        class: Class\To\Inject
        shared: false