diff --git a/src/Symfony/Component/DependencyInjection/Container.php b/src/Symfony/Component/DependencyInjection/Container.php index b97f8a2c038ce..f99eccd401478 100644 --- a/src/Symfony/Component/DependencyInjection/Container.php +++ b/src/Symfony/Component/DependencyInjection/Container.php @@ -184,6 +184,9 @@ public function setParameter($name, $value) /** * Sets a service. * + * Setting a service to null resets the service: has() returns false and get() + * behaves in the same way as if the service was never created. + * * @param string $id The service identifier * @param object $service The service instance * @param string $scope The scope of the service @@ -214,6 +217,14 @@ public function set($id, $service, $scope = self::SCOPE_CONTAINER) if (method_exists($this, $method = 'synchronize'.strtr($id, array('_' => '', '.' => '_')).'Service')) { $this->$method(); } + + if (self::SCOPE_CONTAINER !== $scope && null === $service) { + unset($this->scopedServices[$scope][$id]); + } + + if (null === $service) { + unset($this->services[$id]); + } } /** diff --git a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php index c87f2c2b9ad5d..bb0c728f9374a 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/ContainerTest.php @@ -112,6 +112,16 @@ public function testSet() $this->assertEquals($foo, $sc->get('foo'), '->set() sets a service'); } + /** + * @covers Symfony\Component\DependencyInjection\Container::set + */ + public function testSetWithNullResetTheService() + { + $sc = new Container(); + $sc->set('foo', null); + $this->assertFalse($sc->has('foo')); + } + /** * @expectedException \InvalidArgumentException */