Symfony2 Service Container - returns () returned objects by reference or copy?

Just a quick question, is it interesting to return objects from a service container in Symfony2 by reference or as a copy?

I am asking because I want to know that I am doing something like:

public function helloAction()
{
    $mailer = $this->get('acme.mailer');
    $mailer->shutdown();
}

      

in the controller, and the shutdown () method does something internally to the object, will the acme.mailer service be "shutdown" in the container?

In other words, can I change the service permanently after getting it from the container? Is this good practice?

thank

+2


source to share


1 answer


Services are returned by reference, like all PHP objects (by default).

This does not mean that you will always receive the same instance of a given service.

Each service is defined in an area. The DependencyInjection container provides two common areas:

  • container - every time you request a service, you get the same instance
  • prototype - every time you request a service, you get a new instance


The container volume is standard.

Note : Symfony introduces additional areas.

Learn more about clouds from the official docs: How to work with regions

To answer the second part of the question. If the service is defined in the scope of the container, I don't think it's a good idea to destroy it in the controller. Other parts of the application may still need it. I would rather do shutdown in the destructor.

+5


source







All Articles