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

Lazy services #232

Open
wants to merge 27 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
a0fdad8
Decorate definition when it contains lazy
xepozz Aug 1, 2021
61f2bff
Add tests
xepozz Aug 1, 2021
1b4cfae
Normalize definition out of the building process
xepozz Aug 1, 2021
abb2e83
Rework test cases
xepozz Aug 1, 2021
15f8a66
Add class resolver
xepozz Aug 1, 2021
dbed5b3
Apply fixes from StyleCI
samdark Aug 1, 2021
4bdd4bc
Merge branch 'master' into lazy-services
xepozz Aug 7, 2021
592c239
Fix tests
xepozz Aug 7, 2021
e4bd46f
Apply fixes from StyleCI
samdark Aug 7, 2021
2f8c8b5
Merge branch 'master' into lazy-services
xepozz Aug 10, 2021
8212a39
Merge branch 'master' into lazy-services
xepozz Nov 20, 2022
5136d8d
[ci-review] Apply changes from Rector action.
Nov 20, 2022
47dc088
Fix resolving lazy service
xepozz Nov 20, 2022
40ad592
Merge remote-tracking branch 'origin/lazy-services' into lazy-services
xepozz Nov 20, 2022
125231d
Merge branch 'master' into lazy-services
xepozz Dec 2, 2022
51789d0
Merge branch 'master' into lazy-services
xepozz Dec 3, 2022
1d59fbd
Use `friendsofphp/proxy-manager-lts` package
xepozz Dec 3, 2022
95cdd9e
Fix psalm
xepozz Dec 3, 2022
0b0b784
Rework lazy definition
xepozz Dec 3, 2022
20db77b
Merge branch 'master' into lazy-services
xepozz Jul 29, 2023
d1b0c55
Apply Rector changes (CI)
xepozz Jul 29, 2023
feff3b7
Apply fixes from StyleCI
StyleCIBot Jul 29, 2023
5bf1e81
Fix annotation
xepozz Aug 1, 2023
1d04fbc
Add new test case
xepozz Aug 1, 2023
bc7f70e
Fix psalm
xepozz Aug 1, 2023
fedff5e
Merge branch 'master' into lazy-services
xepozz Mar 3, 2024
51fefa2
Suggestion for lazy service (#355)
vjik Apr 16, 2024
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
4 changes: 3 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
},
"require-dev": {
"league/container": "^3.3",
"ocramius/proxy-manager": "^2.13",
"phpbench/phpbench": "^1.0.0",
"phpunit/phpunit": "^9.4",
"roave/infection-static-analysis-plugin": "^1.6",
Expand All @@ -38,7 +39,8 @@
},
"suggest": {
"yiisoft/injector": "^1.0@dev",
"phpbench/phpbench": "To run benchmarks."
"phpbench/phpbench": "To run benchmarks.",
"ocramius/proxy-manager": "Install this package if you want to use lazy loading."
},
"provide": {
"psr/container-implementation": "1.0.0"
Expand Down
37 changes: 33 additions & 4 deletions src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,20 @@
namespace Yiisoft\Di;

use Closure;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use Psr\Container\ContainerInterface;
use Yiisoft\Di\Contracts\DeferredServiceProviderInterface;
use Yiisoft\Di\Contracts\ServiceProviderInterface;
use Yiisoft\Factory\Definition\ArrayDefinition;
use Yiisoft\Factory\Definition\Decorator\LazyDefinitionDecorator;
use Yiisoft\Factory\Definition\DefinitionInterface;
use Yiisoft\Factory\Definition\DefinitionValidator;
use Yiisoft\Factory\DependencyResolverInterface;
use Yiisoft\Factory\Exception\CircularReferenceException;
use Yiisoft\Factory\Exception\InvalidConfigException;
use Yiisoft\Factory\Exception\NotFoundException;
use Yiisoft\Factory\Exception\NotInstantiableException;
use Yiisoft\Injector\Injector;

use function array_key_exists;
use function array_keys;
use function assert;
Expand All @@ -35,7 +37,8 @@ final class Container extends AbstractContainerConfigurator implements Container
{
private const META_TAGS = 'tags';
private const META_RESET = 'reset';
private const ALLOWED_META = [self::META_TAGS, self::META_RESET];
private const META_LAZY = 'lazy';
private const ALLOWED_META = [self::META_TAGS, self::META_RESET, self::META_LAZY];

/**
* @var array object definitions indexed by their types
Expand Down Expand Up @@ -63,6 +66,7 @@ final class Container extends AbstractContainerConfigurator implements Container

private ?CompositeContainer $rootContainer = null;
private DependencyResolverInterface $dependencyResolver;
private LazyLoadingValueHolderFactory $lazyFactory;

/**
* Container constructor.
Expand Down Expand Up @@ -185,6 +189,7 @@ protected function set(string $id, $definition): void
$this->validateDefinition($definition, $id);
$this->validateMeta($meta);
}
$definition = DefinitionNormalizer::normalize($definition, $id);
xepozz marked this conversation as resolved.
Show resolved Hide resolved

if (isset($meta[self::META_TAGS])) {
if ($this->validate) {
Expand All @@ -195,6 +200,9 @@ protected function set(string $id, $definition): void
if (isset($meta[self::META_RESET])) {
$this->setResetter($id, $meta[self::META_RESET]);
}
if (isset($meta[self::META_LAZY]) && $meta[self::META_LAZY] === true) {
$definition = $this->decorateLazy($id, $definition);
}

unset($this->instances[$id]);
$this->definitions[$id] = $definition;
Expand Down Expand Up @@ -368,9 +376,8 @@ private function buildInternal(string $id)
return $this->buildPrimitive($id);
}
$this->processDefinition($this->definitions[$id]);
$definition = DefinitionNormalizer::normalize($this->definitions[$id], $id);

return $definition->resolve($this->dependencyResolver);
return $this->definitions[$id]->resolve($this->dependencyResolver);
}

/**
Expand Down Expand Up @@ -461,4 +468,26 @@ private function getVariableType($variable): string

return gettype($variable);
}

private function decorateLazy(string $id, DefinitionInterface $definition): DefinitionInterface
{
$factory = $this->getLazyLoadingValueHolderFactory();
if (class_exists($id) || interface_exists($id)) {
$class = $id;
} elseif ($definition instanceof ArrayDefinition) {
$class = $definition->getClass();
} else {
throw new \RuntimeException('Could not determinate object class');
}
xepozz marked this conversation as resolved.
Show resolved Hide resolved

return new LazyDefinitionDecorator($factory, $definition, $class);
}

private function getLazyLoadingValueHolderFactory(): LazyLoadingValueHolderFactory
{
if (!class_exists(LazyLoadingValueHolderFactory::class)) {
throw new \RuntimeException('You should install `ocramius/proxy-manager` if you want to use lazy services.');
}
return $this->lazyFactory ??= new LazyLoadingValueHolderFactory();
xepozz marked this conversation as resolved.
Show resolved Hide resolved
}
}
18 changes: 12 additions & 6 deletions tests/Unit/DefinitionParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,21 +17,25 @@ public function testParseCallableDefinition(): void
$definition = [
'definition' => $fn,
'tags' => ['one', 'two'],
'lazy' => true,
];
[$definition, $meta] = (new DefinitionParser(['tags']))->parse($definition);
[$definition, $meta] = DefinitionParser::parse($definition);

$this->assertSame($fn, $definition);
$this->assertSame(['tags' => ['one', 'two']], $meta);
$this->assertSame(['tags' => ['one', 'two'], 'lazy' => true], $meta);
}

public function testParseArrayCallableDefinition(): void
{
$definition = [
'definition' => [StaticFactory::class, 'create'],
'tags' => ['one', 'two'],
'lazy' => true,
];
[$definition, $meta] = (new DefinitionParser(['tags']))->parse($definition);
[$definition, $meta] = DefinitionParser::parse($definition);

$this->assertSame([StaticFactory::class, 'create'], $definition);
$this->assertSame(['tags' => ['one', 'two']], $meta);
$this->assertSame(['tags' => ['one', 'two'], 'lazy' => true], $meta);
}

public function testParseArrayDefinition(): void
Expand All @@ -40,14 +44,16 @@ public function testParseArrayDefinition(): void
'class' => EngineMarkOne::class,
'__construct()' => [42],
'tags' => ['one', 'two'],
'lazy' => true,
];
[$definition, $meta] = (new DefinitionParser(['tags']))->parse($definition);
[$definition, $meta] = DefinitionParser::parse($definition);

$this->assertSame([
EngineMarkOne::class,
[42],
[],
DefinitionParser::IS_PREPARED_ARRAY_DEFINITION_DATA => true,
], $definition);
$this->assertSame(['tags' => ['one', 'two']], $meta);
$this->assertSame(['tags' => ['one', 'two'], 'lazy' => true], $meta);
}
}
87 changes: 87 additions & 0 deletions tests/Unit/LazyServiceContainerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
<?php

declare(strict_types=1);

namespace Yiisoft\Di\Tests\Unit;

use PHPUnit\Framework\TestCase;
use ProxyManager\Proxy\LazyLoadingInterface;
use Yiisoft\Di\Container;
use Yiisoft\Di\Tests\Support\EngineMarkOne;

class LazyServiceContainerTest extends TestCase
{
public function testIsTheSameObject(): void
{
$class = EngineMarkOne::class;
$number = 55;

$container = new Container([
EngineMarkOne::class => [
'class' => $class,
'setNumber()' => [$number],
'lazy' => true,
],
]);

/* @var \Yiisoft\Di\Tests\Support\EngineMarkOne $object */
$object = $container->get($class);

self::assertInstanceOf(LazyLoadingInterface::class, $object);
self::assertFalse($object->isProxyInitialized());
self::assertEquals($number, $object->getNumber());
self::assertTrue($object->isProxyInitialized());

/* @var \Yiisoft\Di\Tests\Support\EngineMarkOne $object */
$object = $container->get($class);

self::assertInstanceOf(LazyLoadingInterface::class, $object);
self::assertTrue($object->isProxyInitialized());
}

/**
* @dataProvider lazyDefinitionDataProvider
*/
public function testLazy(array $definitions, string $id): void
{
$container = new Container($definitions);

$object = $container->get($id);

self::assertInstanceOf(LazyLoadingInterface::class, $object);
}

public function lazyDefinitionDataProvider(): array
{
return [
'class as key' => [
[EngineMarkOne::class => [
'class' => EngineMarkOne::class,
'lazy' => true,
]],
EngineMarkOne::class,
],
'alias as key' => [
['mark_one' => [
'class' => EngineMarkOne::class,
'lazy' => true,
]],
'mark_one',
],
'dedicated array definition' => [
[EngineMarkOne::class => [
'definition' => ['class' => EngineMarkOne::class],
'lazy' => true,
]],
EngineMarkOne::class,
],
'dedicated callback definition' => [
[EngineMarkOne::class => [
'definition' => fn () => new EngineMarkOne(),
'lazy' => true,
]],
EngineMarkOne::class,
],
];
}
}