Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 711
spdionis Avatar asked Feb 20 '14 15:02

spdionis


People also ask

What is the way to always get a new instance of a service?

This means that each time you retrieve the service, you'll get the same instance. This is usually the behavior you want, but in some cases, you might want to always get a new instance. In order to always get a new instance, set the shared setting to false in your service definition: YAML.

What is di In Symfony?

The Dependency Injection Container in Symfony2 allows components to be injected with their dependencies, and is often used as a Service Locator, which when combined with the DI-container pattern is considered to be an anti-pattern by many.

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.


1 Answers

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
like image 136
martin Avatar answered Oct 21 '22 13:10

martin