Just a quick question, wondering if objects retrieved from the service container in Symfony2 are returned by reference or as a copy?
The reason I ask is because I want to know if I do something like:
public function helloAction()
{
$mailer = $this->get('acme.mailer');
$mailer->shutdown();
}
in a 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 alter a service permanently after getting it from the container? Is this good practice?
Thanks
Services are returned by reference just like all PHP objects (by default).
It doesn’t mean you will always get the same instance of a given service though.
Each service is defined in a scope. DependencyInjection container provides two generic scopes:
Container scope is the default one.
Note: Symfony introduces additional scopes.
Learn more about scopes from the official documentation: How to work with Scopes
To answer second part of the question. If a service is defined in a container scope I don’t think it’s a good idea to destroy it in the controller. Other parts of your application might still be needing it. I’d rather perform shutdown in a destructor.