Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony create new service as a new instance

Tags:

php

symfony

I have a service defined with several dependency injections in the constructor. At some point I want to get the service as a new instance instead of the same instance already created. Note that normally I want the service to be shared, but on an edge case I want to create a new instance, so the shared option in the service definition is not aplicable.

I can create a new object, but I then I would have to inject the dependencies manually, and I would prefer to let symfony to deal with it.

So how can I tell Symfony to return a service as a new instance?

Thank you.

like image 517
David Rojo Avatar asked Nov 13 '17 16:11

David Rojo


People also ask

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

In order to always get a new instance, set the shared setting to false in your service definition: YAML. XML.

Are Symfony services singletons?

symfony2 service is not a singleton.

What is a service configurator in Symfony?

The service configurator is a feature of the service container that allows you to use a callable to configure a service after its instantiation. A service configurator can be used, for example, when you have a service that requires complex setup based on configuration settings coming from different sources/services.

What is Symfony Service Container?

In Symfony, these useful objects are called services and each service lives inside a very special object called the service container. The container allows you to centralize the way objects are constructed. It makes your life easier, promotes a strong architecture and is super fast!


1 Answers

As far as I know, there is no way to tell the Symfony Dependency Injection Container to return some times the shared instance, and other times a new instance of a service.

By default, the services are shared, as you already found out. You can tell the container to create a not-shared service by setting the shared setting to false in your service definition:

# app/config/services.yml
services:
    AppBundle\SomeNonSharedService:
        shared: false

Armed with this knowledge, I think the solution for your issue is to create a duplicate of the shared service with a different name and mark it as not-shared as explained above. When you ask the container to get the duplicate, it will create a new instance every time.

Do not attempt to create the duplicate as an alias of the original service, it doesn't work. The first thing the implementation of Contaner::get() does is to search for the service ID provided as argument into the list of aliases and use the ID of the original service instead if it finds it there.

like image 168
axiac Avatar answered Oct 26 '22 14:10

axiac