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 1 commit
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
Prev Previous commit
Next Next commit
Add docs
  • Loading branch information
xepozz committed Feb 23, 2024
commit f6856a68b58dbcd9651d260a543f3af1e55fa7e3
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

## 1.2.2 under development

- no changes in this release.
- Enh #354: Add ability to use container as a factory (@xepozz)

## 1.2.1 December 23, 2022

Expand Down
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,40 @@ $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
*/
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
Loading