Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to use container as a factory #354

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## 1.2.2 under development

- Enh #354: Add ability to use container as a factory (@xepozz)
- Enh #353: Add shortcut for tag reference #333 (@xepozz)

## 1.2.1 December 23, 2022
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,41 @@ $config = ContainerConfig::create()
$container = new Container($config);
```

## Using the container as a factory

You can use the container as a factory to create objects.
This is useful when you need to create an object every time from the bottom.

```php
use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Di\Hook\AfterBuiltHook;

$config = ContainerConfig::create()
->withDefinitions([
BlueCarService::class => [
'class' => BlueCarService::class,
'afterBuilt' => AfterBuiltHook::unsetInstance(), // it will be called after the object is created
],
]);

$container = new Container($config);

$container->get(BlueCarService::class) !== $container->get(BlueCarService::class); // true
```

You may use `afterBuilt` as you want. The value of the key must be a callable with the following signature:

```php
function (Container $container, string $id) {
/**
* @var $this Container
*/
/** @psalm-scope-this Container */
unset($this->instances[$id]); // remove the instance from the container
};
```

## Resetting services state

Despite stateful services isn't a great practice, these are often inevitable. When you build long-running
Expand Down
33 changes: 29 additions & 4 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ final class Container implements ContainerInterface
{
private const META_TAGS = 'tags';
private const META_RESET = 'reset';
private const ALLOWED_META = [self::META_TAGS, self::META_RESET];
private const META_AFTER_BUILT = 'afterBuilt';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are there any other cases for this hook?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not now

private const ALLOWED_META = [self::META_TAGS, self::META_RESET, self::META_AFTER_BUILT];

/**
* @var DefinitionStorage Storage of object definitions.
Expand Down Expand Up @@ -67,6 +68,12 @@ final class Container implements ContainerInterface
* @var Closure[]
*/
private array $resetters = [];

/**
* @var Closure[]
*/
public array $afterBuiltHooks = [];

private bool $useResettersFromMeta = true;

/**
Expand Down Expand Up @@ -134,10 +141,12 @@ public function has(string $id): bool
*/
public function get(string $id)
{
$result = null;
if (!array_key_exists($id, $this->instances)) {
try {
try {
$this->instances[$id] = $this->build($id);
/** @psalm-suppress MixedAssignment */
$result = $this->instances[$id] = $this->build($id);
} catch (NotFoundExceptionInterface $e) {
if (!$this->delegates->has($id)) {
throw $e;
Expand All @@ -153,6 +162,7 @@ public function get(string $id)
throw new BuildingException($id, $e, $this->definitions->getBuildStack(), $e);
}
}
$this->callHookAfterBuilt($id);

if ($id === StateResetter::class) {
$delegatesResetter = null;
Expand Down Expand Up @@ -184,7 +194,7 @@ public function get(string $id)
}

/** @psalm-suppress MixedReturnStatement */
return $this->instances[$id];
return $result ?? $this->instances[$id];
}

/**
Expand All @@ -206,7 +216,7 @@ private function addDefinition(string $id, mixed $definition): void
$this->validateMeta($meta);
}
/**
* @psalm-var array{reset?:Closure,tags?:string[]} $meta
* @psalm-var array{reset?:Closure,tags?:string[],afterBuilt?:Closure} $meta
*/

if (isset($meta[self::META_TAGS])) {
Expand All @@ -215,6 +225,9 @@ private function addDefinition(string $id, mixed $definition): void
if (isset($meta[self::META_RESET])) {
$this->setDefinitionResetter($id, $meta[self::META_RESET]);
}
if (isset($meta[self::META_AFTER_BUILT])) {
$this->setAfterBuiltHook($id, $meta[self::META_AFTER_BUILT]);
}

unset($this->instances[$id]);
$this->addDefinitionToStorage($id, $definition);
Expand Down Expand Up @@ -621,4 +634,16 @@ private function buildProvider(mixed $provider): ServiceProviderInterface

return $providerInstance;
}

private function callHookAfterBuilt(string $id): void
{
if (isset($this->afterBuiltHooks[$id])) {
$this->afterBuiltHooks[$id]->call($this, $this, $id);
}
}

private function setAfterBuiltHook(string $id, Closure $callback): void
{
$this->afterBuiltHooks[$id] = $callback;
}
}
22 changes: 22 additions & 0 deletions src/Hook/AfterBuiltHook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Di\Hook;

use Closure;
use Yiisoft\Di\Container;

final class AfterBuiltHook
{
public static function unsetInstance(): Closure
{
return function (Container $container, string $id) {
/**
* @var $this Container
*/
/** @psalm-scope-this Container */
unset($this->instances[$id]);
};
}
}
32 changes: 32 additions & 0 deletions tests/Unit/Hook/AfterBuiltHookTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

declare(strict_types=1);

namespace Unit\Hook;

use PHPUnit\Framework\TestCase;
use Yiisoft\Di\Container;
use Yiisoft\Di\ContainerConfig;
use Yiisoft\Di\Hook\AfterBuiltHook;
use Yiisoft\Di\Tests\Support\EngineInterface;
use Yiisoft\Di\Tests\Support\EngineMarkOne;

final class AfterBuiltHookTest extends TestCase
{
public function testDifferentObjects()
{
$config = ContainerConfig::create()
->withDefinitions([
EngineInterface::class => [
'class' => EngineMarkOne::class,
'afterBuilt' => AfterBuiltHook::unsetInstance(),
],
]);
$container = new Container($config);

$this->assertNotSame(
$container->get(EngineInterface::class),
$container->get(EngineInterface::class),
);
}
}