Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2 service with multiple instances?

Tags:

php

symfony

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?

like image 987
Tower Avatar asked Mar 26 '12 09:03

Tower


2 Answers

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
like image 145
Sgoettschkes Avatar answered Sep 22 '22 02:09

Sgoettschkes


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

like image 38
Laoneo Avatar answered Sep 26 '22 02:09

Laoneo