trentlor
trentlor

Reputation: 11

How to get several objects of same class by Symfony Dependency Injection (Recursively)?

I'm trying to get objects of same class but with various property values, using Symfony DI, but I receive identical objects. I had tried explore Symfony doc, but I can't find the answer.

<?php

use Symfony\Component\DependencyInjection\ContainerBuilder;


class Foo
{
    public $container;
    public $booCollection = [];

    public function __construct()
    {
        $this->container = $container = new ContainerBuilder();
        $this->container->setParameter('id', '');
        $this->container->register('boo', 'Boo')
            ->addArgument('%booid%');
    }

    public function getListOfBoo()
    {
        for ($id = 1; $id <= 2; $id++) {
            $this->container->setParameter('booid', $id);
            $this->booCollection[] = $this->container->get('boo');
        }
    }
}

class Boo
{
    public $id;
    public function __construct($id)
    {
        $this->id = $id;
    }
}

$foo = new Foo();
$foo->getListOfBoo();

var_dump($foo->booCollection);
?>

Result:

array (size=2)
    0 => 
        object(Boo)[32]
        public 'id' => int 1
    1 => 
        object(Boo)[32]
        public 'id' => int 1

But I need to:

array (size=2)
    0 => 
        object(Boo)[32]
        public 'id' => int 1
    1 => 
        object(Boo)[32]
        public 'id' => int 2

Upvotes: 1

Views: 291

Answers (1)

Richard
Richard

Reputation: 4129

You need to either use the prototype scope (symfony < 2.8) or set shared to false in your service definition (symfony >= 2.8).

E.g. (< 2.8)

services:
    app.some_not_shared_service:
        class: ...
        scope: prototype

E.g. (>= 2.8)

services:
    app.some_not_shared_service:
        class: ...
        shared: false

For more information:

http://symfony.com/doc/2.8/cookbook/service_container/shared.html

Upvotes: 1

Related Questions