Skip to content

[DependencyInjection] Use WeakReference to break circular references in the container #48469

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

Merged
merged 1 commit into from
Dec 9, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,17 @@ public function getProxyFactoryCode(Definition $definition, string $id, string $
$instantiation = 'return';

if ($definition->isShared()) {
$instantiation .= sprintf(' $this->%s[%s] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', var_export($id, true));
$instantiation .= sprintf(' $container->%s[%s] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', var_export($id, true));
}

$proxifiedClass = new \ReflectionClass($this->proxyGenerator->getProxifiedClass($definition));
$proxyClass = $this->getProxyClassName($proxifiedClass->name);

return <<<EOF
if (true === \$lazyLoad) {
$instantiation \$this->createProxy('$proxyClass', function () {
return \\$proxyClass::staticProxyConstructor(function (&\$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface \$proxy) {
$instantiation \$container->createProxy('$proxyClass', static function () use (\$containerRef) {
return \\$proxyClass::staticProxyConstructor(static function (&\$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface \$proxy) use (\$containerRef) {
\$container = \$containerRef->get();
\$wrappedInstance = $factoryCode;

\$proxy->setProxyInitializer(null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,15 @@
use %a
class LazyServiceProjectServiceContainer extends Container
{%a
protected function getFooService($lazyLoad = true)
protected static function getFooService($container, $lazyLoad = true)
{
$containerRef = $container->ref;

if (true === $lazyLoad) {
return $this->services['foo'] = $this->createProxy('stdClass_%s', function () {
return %S\stdClass_%s(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
$wrappedInstance = $this->getFooService(false);
return $container->services['foo'] = $container->createProxy('stdClass_%s', static function () use ($containerRef) {
return %S\stdClass_%s(static function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) use ($containerRef) {
$container = $containerRef->get();
$wrappedInstance = self::getFooService($containerRef->get(), false);

$proxy->setProxyInitializer(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@

public function getFooService($lazyLoad = true)
{
$container = $this;
$containerRef = \WeakReference::create($this);

if (true === $lazyLoad) {
return $this->privates['foo'] = $this->createProxy('SunnyInterface_1eff735', function () {
return \SunnyInterface_1eff735::staticProxyConstructor(function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) {
$wrappedInstance = $this->getFooService(false);
return $container->privates['foo'] = $container->createProxy('SunnyInterface_1eff735', static function () use ($containerRef) {
return \SunnyInterface_1eff735::staticProxyConstructor(static function (&$wrappedInstance, \ProxyManager\Proxy\LazyLoadingInterface $proxy) use ($containerRef) {
$container = $containerRef->get();
$wrappedInstance = $container->getFooService(false);

$proxy->setProxyInitializer(null);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ public function testGetProxyFactoryCode()

$definition->setLazy(true);

$code = $this->dumper->getProxyFactoryCode($definition, 'foo', '$this->getFoo2Service(false)');
$code = $this->dumper->getProxyFactoryCode($definition, 'foo', '$container->getFoo2Service(false)');

$this->assertStringMatchesFormat(
'%A$wrappedInstance = $this->getFoo2Service(false);%w$proxy->setProxyInitializer(null);%A',
'%A$wrappedInstance = $container->getFoo2Service(false);%w$proxy->setProxyInitializer(null);%A',
$code
);
}
Expand All @@ -87,9 +87,9 @@ public function testCorrectAssigning(Definition $definition, $access)
{
$definition->setLazy(true);

$code = $this->dumper->getProxyFactoryCode($definition, 'foo', '$this->getFoo2Service(false)');
$code = $this->dumper->getProxyFactoryCode($definition, 'foo', '$container->getFoo2Service(false)');

$this->assertStringMatchesFormat('%A$this->'.$access.'[\'foo\'] = %A', $code);
$this->assertStringMatchesFormat('%A$container->'.$access.'[\'foo\'] = %A', $code);
}

public function getPrivatePublicDefinitions()
Expand Down Expand Up @@ -118,7 +118,7 @@ public function testGetProxyFactoryCodeForInterface()
$definition->addTag('proxy', ['interface' => SunnyInterface::class]);

$implem = "<?php\n\n".$this->dumper->getProxyCode($definition);
$factory = $this->dumper->getProxyFactoryCode($definition, 'foo', '$this->getFooService(false)');
$factory = $this->dumper->getProxyFactoryCode($definition, 'foo', '$container->getFooService(false)');
$factory = <<<EOPHP
<?php

Expand All @@ -129,6 +129,9 @@ public function testGetProxyFactoryCodeForInterface()

public function getFooService(\$lazyLoad = true)
{
\$container = \$this;
\$containerRef = \\WeakReference::create(\$this);

{$factory} return new {$class}();
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/ProxyManager/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"require": {
"php": ">=8.1",
"friendsofphp/proxy-manager-lts": "^1.0.2",
"symfony/dependency-injection": "^6.2",
"symfony/dependency-injection": "^6.3",
"symfony/deprecation-contracts": "^2.1|^3"
},
"require-dev": {
Expand Down
38 changes: 20 additions & 18 deletions src/Symfony/Component/DependencyInjection/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ class Container implements ContainerInterface, ResetInterface
private bool $compiled = false;
private \Closure $getEnv;

private static $make;

public function __construct(ParameterBagInterface $parameterBag = null)
{
$this->parameterBag = $parameterBag ?? new EnvPlaceholderParameterBag();
Expand Down Expand Up @@ -135,7 +137,7 @@ public function set(string $id, ?object $service)
if (isset($this->privates['service_container']) && $this->privates['service_container'] instanceof \Closure) {
$initialize = $this->privates['service_container'];
unset($this->privates['service_container']);
$initialize();
$initialize($this);
}

if ('service_container' === $id) {
Expand Down Expand Up @@ -195,49 +197,49 @@ public function get(string $id, int $invalidBehavior = self::EXCEPTION_ON_INVALI
{
return $this->services[$id]
?? $this->services[$id = $this->aliases[$id] ?? $id]
?? ('service_container' === $id ? $this : ($this->factories[$id] ?? $this->make(...))($id, $invalidBehavior));
?? ('service_container' === $id ? $this : ($this->factories[$id] ?? self::$make ??= self::make(...))($this, $id, $invalidBehavior));
}

/**
* Creates a service.
*
* As a separate method to allow "get()" to use the really fast `??` operator.
*/
private function make(string $id, int $invalidBehavior)
private static function make($container, string $id, int $invalidBehavior)
{
if (isset($this->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_merge(array_keys($this->loading), [$id]));
if (isset($container->loading[$id])) {
throw new ServiceCircularReferenceException($id, array_merge(array_keys($container->loading), [$id]));
}

$this->loading[$id] = true;
$container->loading[$id] = true;

try {
if (isset($this->fileMap[$id])) {
return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->load($this->fileMap[$id]);
} elseif (isset($this->methodMap[$id])) {
return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $this->{$this->methodMap[$id]}();
if (isset($container->fileMap[$id])) {
return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $container->load($container->fileMap[$id]);
} elseif (isset($container->methodMap[$id])) {
return /* self::IGNORE_ON_UNINITIALIZED_REFERENCE */ 4 === $invalidBehavior ? null : $container->{$container->methodMap[$id]}($container);
}
} catch (\Exception $e) {
unset($this->services[$id]);
unset($container->services[$id]);

throw $e;
} finally {
unset($this->loading[$id]);
unset($container->loading[$id]);
}

if (self::EXCEPTION_ON_INVALID_REFERENCE === $invalidBehavior) {
if (!$id) {
throw new ServiceNotFoundException($id);
}
if (isset($this->syntheticIds[$id])) {
if (isset($container->syntheticIds[$id])) {
throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service is synthetic, it needs to be set at boot time before it can be used.', $id));
}
if (isset($this->getRemovedIds()[$id])) {
if (isset($container->getRemovedIds()[$id])) {
throw new ServiceNotFoundException($id, null, null, [], sprintf('The "%s" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.', $id));
}

$alternatives = [];
foreach ($this->getServiceIds() as $knownId) {
foreach ($container->getServiceIds() as $knownId) {
if ('' === $knownId || '.' === $knownId[0]) {
continue;
}
Expand Down Expand Up @@ -378,13 +380,13 @@ final protected function getService(string|false $registry, string $id, ?string
return false !== $registry ? $this->{$registry}[$id] ?? null : null;
}
if (false !== $registry) {
return $this->{$registry}[$id] ??= $load ? $this->load($method) : $this->{$method}();
return $this->{$registry}[$id] ??= $load ? $this->load($method) : $this->{$method}($this);
}
if (!$load) {
return $this->{$method}();
return $this->{$method}($this);
}

return ($factory = $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory() : $this->load($method);
return ($factory = $this->factories[$id] ?? $this->factories['service_container'][$id] ?? null) ? $factory($this) : $this->load($method);
}

private function __clone()
Expand Down
Loading