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 @@
{
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
Contributor 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 @@
* @var Closure[]
*/
private array $resetters = [];

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

private bool $useResettersFromMeta = true;

/**
Expand Down Expand Up @@ -134,10 +141,12 @@
*/
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 @@
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 @@
}

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

Check warning on line 197 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "Coalesce": --- Original +++ New @@ @@ } } /** @psalm-suppress MixedReturnStatement */ - return $result ?? $this->instances[$id]; + return $this->instances[$id] ?? $result; } /** * Sets a definition to the container. Definition may be defined multiple ways.

Check warning on line 197 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "Coalesce": --- Original +++ New @@ @@ } } /** @psalm-suppress MixedReturnStatement */ - return $result ?? $this->instances[$id]; + return $this->instances[$id] ?? $result; } /** * Sets a definition to the container. Definition may be defined multiple ways.
}

/**
Expand All @@ -206,7 +216,7 @@
$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 @@
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 @@ -276,7 +289,7 @@

$this->delegates->attach($delegate);
}
$this->definitions->setDelegateContainer($this->delegates);

Check warning on line 292 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "MethodCallRemoval": --- Original +++ New @@ @@ } $this->delegates->attach($delegate); } - $this->definitions->setDelegateContainer($this->delegates); + } /** * @param mixed $definition Definition to validate.

Check warning on line 292 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "MethodCallRemoval": --- Original +++ New @@ @@ } $this->delegates->attach($delegate); } - $this->definitions->setDelegateContainer($this->delegates); + } /** * @param mixed $definition Definition to validate.
}

/**
Expand All @@ -303,7 +316,7 @@

$definition = array_merge(
$class === null ? [] : [ArrayDefinition::CLASS_NAME => $class],
[ArrayDefinition::CONSTRUCTOR => $constructorArguments],

Check warning on line 319 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "ArrayItemRemoval": --- Original +++ New @@ @@ $methodsAndProperties = $definition['methodsAndProperties']; $definition = array_merge( $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class], - [ArrayDefinition::CONSTRUCTOR => $constructorArguments], + [], // extract only value from parsed definition method array_map(fn(array $data): mixed => $data[2], $methodsAndProperties) );

Check warning on line 319 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "ArrayItemRemoval": --- Original +++ New @@ @@ $methodsAndProperties = $definition['methodsAndProperties']; $definition = array_merge( $class === null ? [] : [ArrayDefinition::CLASS_NAME => $class], - [ArrayDefinition::CONSTRUCTOR => $constructorArguments], + [], // extract only value from parsed definition method array_map(fn(array $data): mixed => $data[2], $methodsAndProperties) );
// extract only value from parsed definition method
array_map(fn (array $data): mixed => $data[2], $methodsAndProperties),
);
Expand Down Expand Up @@ -489,7 +502,7 @@
);
}

$this->building[$id] = 1;

Check warning on line 505 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "IncrementInteger": --- Original +++ New @@ @@ } throw new CircularReferenceException(sprintf('Circular reference to "%s" detected while building: %s.', $id, implode(', ', array_keys($this->building)))); } - $this->building[$id] = 1; + $this->building[$id] = 2; try { /** @var mixed $object */ $object = $this->buildInternal($id);

Check warning on line 505 in src/Container.php

View workflow job for this annotation

GitHub Actions / mutation / PHP 8.1-ubuntu-latest

Escaped Mutant for Mutator "IncrementInteger": --- Original +++ New @@ @@ } throw new CircularReferenceException(sprintf('Circular reference to "%s" detected while building: %s.', $id, implode(', ', array_keys($this->building)))); } - $this->building[$id] = 1; + $this->building[$id] = 2; try { /** @var mixed $object */ $object = $this->buildInternal($id);
try {
/** @var mixed $object */
$object = $this->buildInternal($id);
Expand Down Expand Up @@ -621,4 +634,16 @@

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]);

Check failure on line 19 in src/Hook/AfterBuiltHook.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.0-ubuntu-latest

UndefinedDocblockClass

src/Hook/AfterBuiltHook.php:19:13: UndefinedDocblockClass: Scope class Container does not exist (see https://psalm.dev/200)

Check failure on line 19 in src/Hook/AfterBuiltHook.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.0-ubuntu-latest

InvalidScope

src/Hook/AfterBuiltHook.php:19:19: InvalidScope: Invalid reference to $this in a non-class context (see https://psalm.dev/013)

Check failure on line 19 in src/Hook/AfterBuiltHook.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.0-ubuntu-latest

UndefinedDocblockClass

src/Hook/AfterBuiltHook.php:19:13: UndefinedDocblockClass: Scope class Container does not exist (see https://psalm.dev/200)

Check failure on line 19 in src/Hook/AfterBuiltHook.php

View workflow job for this annotation

GitHub Actions / psalm / PHP 8.0-ubuntu-latest

InvalidScope

src/Hook/AfterBuiltHook.php:19:19: InvalidScope: Invalid reference to $this in a non-class context (see https://psalm.dev/013)
};
}
}
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),
);
}
}
Loading