Skip to content

Commit 7291b14

Browse files
authored
Fixed method define does not works when the class has been resolved. (#2695)
* Fixed method `define` does not works when the class has been resolved. * Added test cases.
1 parent ab75a0b commit 7291b14

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/Container.php

+5-2
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ public function set(string $name, $entry)
100100
*/
101101
public function define(string $name, $definition)
102102
{
103-
$this->definitionSource->addDefinition($name, $definition);
103+
$this->setDefinition($name, $definition);
104104
}
105105

106106
/**
@@ -153,7 +153,10 @@ public function getDefinitionSource(): Definition\DefinitionSourceInterface
153153
return $this->definitionSource;
154154
}
155155

156-
protected function setDefinition(string $name, DefinitionInterface $definition): void
156+
/**
157+
* @param array|callable|string $definition
158+
*/
159+
private function setDefinition(string $name, $definition): void
157160
{
158161
// Clear existing entry if it exists
159162
if (array_key_exists($name, $this->resolvedEntries)) {

tests/ContainerTest.php

+12
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@
1313

1414
use Hyperf\Di\Container;
1515
use Hyperf\Di\Definition\DefinitionSource;
16+
use HyperfTest\Di\Stub\Bar;
1617
use HyperfTest\Di\Stub\Foo;
1718
use HyperfTest\Di\Stub\FooInterface;
19+
use Mockery;
1820
use PHPUnit\Framework\TestCase;
1921

2022
/**
@@ -23,6 +25,11 @@
2325
*/
2426
class ContainerTest extends TestCase
2527
{
28+
protected function tearDown(): void
29+
{
30+
Mockery::close();
31+
}
32+
2633
public function testHas()
2734
{
2835
$container = new Container(new DefinitionSource([]));
@@ -44,5 +51,10 @@ public function testDefine()
4451
$container = new Container(new DefinitionSource([]));
4552
$container->define(FooInterface::class, Foo::class);
4653
$this->assertInstanceOf(Foo::class, $container->make(FooInterface::class));
54+
55+
$container->define(FooInterface::class, function () {
56+
return Mockery::mock(Bar::class);
57+
});
58+
$this->assertInstanceOf(Bar::class, $foo = $container->make(FooInterface::class));
4759
}
4860
}

0 commit comments

Comments
 (0)