I read this: http://symfony.com/doc/current/book/service_container.html
It said:
$mailer = $this->get('my_mailer');
As an added bonus, the Mailer service is only created once and the same instance is returned each time you ask for the service. This is almost always the behavior you'll need (it's more flexible and powerful), but we'll learn later how you can configure a service that has multiple instances.
How do I make my service to have multiple instances -- i.e. whenever I reach the service I am given a new instance? Something like $this->getNew()
or something?
You are talking about the scope of a service. You can look them up here. In short, define your service as scope prototype instead of the default container and the dependency injection container will take care to create a new object every time you request it:
services:
my_service:
class: Someclass
scope: prototype
Note: since Symfony2.8, scope: prototype
has been replaced by shared: false
.
# Symfony >= 2.8
services:
my_service:
class: Someclass
shared: false
In Symfony >= 2.8 the scope attribute was deprecated and in version 3 removed. You need to use the shared setting as described here http://symfony.com/doc/current/cookbook/service_container/shared.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With