Skip to content
Permalink
Browse files

#674 Special interpretation of `\DI\value` in `\DI\Container::se… (#675)

#674 Special interpretation of `\DI\value` in `\DI\Container::set`
  • Loading branch information...
mnapoli committed Jul 8, 2019
2 parents 806ca40 + 7ee0fcf commit 00a5eb0f0dd94deabb71acfbf44c37b80d53d0a1
Showing with 31 additions and 1 deletion.
  1. +4 −0 doc/container.md
  2. +4 −1 src/Container.php
  3. +23 −0 tests/IntegrationTest/ContainerSetTest.php
@@ -30,6 +30,10 @@ You can set entries directly on the container:
```php
$container->set('foo', 'bar');
$container->set('MyInterface', \DI\create('MyClass'));
// Use \DI\value if you need to set a closure as raw value,
// because closures are interpreted as factories by default
$container->set('myClosure', \DI\value(function() { /* ... */ }));
```

However it is recommended to use definition files. See the [definition documentation](definition.md).
@@ -16,6 +16,7 @@
use DI\Definition\Source\MutableDefinitionSource;
use DI\Definition\Source\ReflectionBasedAutowiring;
use DI\Definition\Source\SourceChain;
use DI\Definition\ValueDefinition;
use DI\Invoker\DefinitionParameterResolver;
use DI\Proxy\ProxyFactory;
use InvalidArgumentException;
@@ -282,7 +283,9 @@ public function set(string $name, $value)
$value = new FactoryDefinition($name, $value);
}
if ($value instanceof Definition) {
if ($value instanceof ValueDefinition) {
$this->resolvedEntries[$name] = $value->getValue();
} elseif ($value instanceof Definition) {
$value->setName($name);
$this->setDefinition($name, $value);
} else {
@@ -7,6 +7,7 @@
use DI\ContainerBuilder;
use function DI\create;
use function DI\get;
use function DI\value;
/**
* Tests the set() method from the container.
@@ -58,6 +59,28 @@ public function array_entries_can_be_overridden_by_values(ContainerBuilder $buil
$this->assertSame('hello', $container->get('foo'));
}
/**
* @see https://github.com/PHP-DI/PHP-DI/issues/674
* @test
* @dataProvider provideContainer
*/
public function value_definitions_are_interpreted_as_raw_values(ContainerBuilder $builder)
{
$container = $builder->build();
$foo = 'foo';
$bar = new ContainerSetTest\Dummy();
$baz = function() {};
$container->set('foo', value($foo));
$container->set('bar', value($bar));
$container->set('baz', value($baz));
$this->assertSame($foo, $container->get('foo'));
$this->assertSame($bar, $container->get('bar'));
$this->assertSame($baz, $container->get('baz'));
}
/**
* @test
* @dataProvider provideContainer

0 comments on commit 00a5eb0

Please sign in to comment.
You can’t perform that action at this time.