我试图使用Symfony DI来获取同一类但具有各种属性值的对象,但我收到了相同的对象。我曾尝试过探索Symfony doc,但我无法找到答案。
<?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);
?>
结果:
array (size=2)
0 =>
object(Boo)[32]
public 'id' => int 1
1 =>
object(Boo)[32]
public 'id' => int 1
但我需要:
array (size=2)
0 =>
object(Boo)[32]
public 'id' => int 1
1 =>
object(Boo)[32]
public 'id' => int 2
答案 0 :(得分:1)
您需要使用原型范围(symfony&lt; 2.8)或在服务定义中将shared设置为false(symfony&gt; = 2.8)。
E.g。 (&lt; 2.8)
services:
app.some_not_shared_service:
class: ...
scope: prototype
E.g。 (&gt; = 2.8)
services:
app.some_not_shared_service:
class: ...
shared: false
了解更多信息:
http://symfony.com/doc/2.8/cookbook/service_container/shared.html