Closed
Description
Q | A |
---|---|
Bug report? | yes |
Feature request? | no |
BC Break report? | yes |
RFC? | no |
Symfony version | > 3.2 |
# di-bug.yml
services:
dependent_collection:
class: DependantCollection
calls:
- [addDependant, ['@dependent_1']]
- [addDependant, ['@dependent_2']]
dependent_1:
class: Dependent
calls:
- [setName, ['dependent_1']]
- [setDependency, ['@dependency']]
shared: false
dependent_2:
class: Dependent
calls:
- [setName, ['dependent_2']]
- [setDependency, ['@dependency']]
shared: false
dependency:
class: Dependency
shared: false
<?php
// di-bug.php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class DependantCollection
{
protected $_dependents = [];
public function addDependant(Dependent $dependent): DependantCollection
{
if (isset($this->_dependents[$dependent->getName()])) {
throw new \LogicException('Dependent with name ' . $dependent->getName() . 'is already set.');
}
$this->_dependents[$dependent->getName()] = $dependent;
return $this;
}
}
class Dependent
{
protected $_dependency;
protected $_name;
public function setDependency(Dependency $dependency): Dependent
{
if ($this->_dependency === null) {
$dependency->setDependent($this);
$this->_dependency = $dependency;
}else {
throw new \LogicException('Dependency is already set.');
}
return $this;
}
public function setName(string $name): Dependent
{
if ($this->_name === null) {
$this->_name = $name;
}else {
throw new \LogicException('Name is already set.');
}
return $this;
}
public function getName(): string
{
if ($this->_name === null) {
throw new \LogicException('Name is not set.');
}
return $this->_name;
}
}
class Dependency
{
protected $_dependent;
public function setDependent(Dependent $dependent): Dependency
{
if ($this->_dependent === null) {
$this->_dependent = $dependent;
}else {
throw new \LogicException('Dependent is already set.');
}
return $this;
}
}
$containerBuilder = new ContainerBuilder();
$loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
$loader->load('./di-bug.yml');
$dependentCollection = $containerBuilder->get('dependent_collection');
return;
Notice that the first pass injects a Dependency
into the first Dependent
, however the reference to Dependency
is maintained and the same Dependency
is injected into the second Dependent
resulting in a LogicException
with the message Dependent is already set.
since it is the same Dependency
object as was passed to the first Dependent
.
This works correctly in 3.2.
Metadata
Metadata
Assignees
Labels
No labels