Skip to content

[DependencyInjection] [ProxyManager] Use lazy-loading ghost object proxies when possible #46458

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

Closed
wants to merge 1 commit into from
Closed
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
42 changes: 27 additions & 15 deletions src/Symfony/Bridge/Doctrine/ManagerRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,26 +50,38 @@ protected function resetService($name): void
if (!$manager instanceof LazyLoadingInterface) {
throw new \LogicException('Resetting a non-lazy manager service is not supported. '.(interface_exists(LazyLoadingInterface::class) && class_exists(RuntimeInstantiator::class) ? sprintf('Declare the "%s" service as lazy.', $name) : 'Try running "composer require symfony/proxy-manager-bridge".'));
}

$load = \Closure::bind(function () use ($name) {
if (isset($this->aliases[$name])) {
$name = $this->aliases[$name];
}
if (isset($this->fileMap[$name])) {
return fn ($lazyLoad) => $this->load($this->fileMap[$name], $lazyLoad);
}

return $this->{$this->methodMap[$name]}(...);
}, $this->container, Container::class)();

if ($manager instanceof GhostObjectInterface) {
throw new \LogicException('Resetting a lazy-ghost-object manager service is not supported.');
}
$manager->setProxyInitializer(\Closure::bind(
function (&$wrappedInstance, LazyLoadingInterface $manager) use ($name) {
if (isset($this->aliases[$name])) {
$name = $this->aliases[$name];
}
if (isset($this->fileMap[$name])) {
$wrappedInstance = $this->load($this->fileMap[$name], false);
} else {
$wrappedInstance = $this->{$this->methodMap[$name]}(false);
$initializer = function (GhostObjectInterface $manager, string $method, array $parameters, &$initializer, array $properties) use ($load) {
$instance = $load($manager);
$initializer = null;

if ($instance !== $manager) {
throw new \LogicException(sprintf('A lazy initializer should return the ghost object proxy it was given as argument, but an instance of "%s" was returned.', get_debug_type($instance)));
}

return true;
};
} else {
$initializer = function (&$wrappedInstance, LazyLoadingInterface $manager) use ($load) {
$wrappedInstance = $load(false);
$manager->setProxyInitializer(null);

return true;
},
$this->container,
Container::class
));
};
}

$manager->setProxyInitializer($initializer);
}
}
23 changes: 10 additions & 13 deletions src/Symfony/Bridge/Doctrine/Tests/ManagerRegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
namespace Symfony\Bridge\Doctrine\Tests;

use PHPUnit\Framework\TestCase;
use ProxyManager\Proxy\LazyLoadingInterface;
use ProxyManager\Proxy\ValueHolderInterface;
use ProxyManager\Proxy\GhostObjectInterface;
use Symfony\Bridge\Doctrine\ManagerRegistry;
use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
use Symfony\Bridge\ProxyManager\Tests\LazyProxy\Dumper\PhpDumperTest;
Expand All @@ -38,13 +37,16 @@ public function testResetService()
$registry->setTestContainer($container);

$foo = $container->get('foo');
$foo->bar = 123;
$this->assertTrue(isset($foo->bar));

$foo->bar = 234;
$this->assertSame(234, $foo->bar);
$registry->resetManager();

self::assertFalse($foo->isProxyInitialized());
$foo->initializeProxy();

$this->assertSame($foo, $container->get('foo'));
$this->assertObjectNotHasAttribute('bar', $foo);
$this->assertSame(123, $foo->bar);
}

/**
Expand Down Expand Up @@ -77,8 +79,7 @@ public function testResetServiceWillNotNestFurtherLazyServicesWithinEachOther()
$service = $container->get('foo');

self::assertInstanceOf(\stdClass::class, $service);
self::assertInstanceOf(LazyLoadingInterface::class, $service);
self::assertInstanceOf(ValueHolderInterface::class, $service);
self::assertInstanceOf(GhostObjectInterface::class, $service);
self::assertFalse($service->isProxyInitialized());

$service->initializeProxy();
Expand All @@ -87,12 +88,7 @@ public function testResetServiceWillNotNestFurtherLazyServicesWithinEachOther()
self::assertTrue($service->isProxyInitialized());

$registry->resetManager();
$service->initializeProxy();

$wrappedValue = $service->getWrappedValueHolderValue();
self::assertInstanceOf(\stdClass::class, $wrappedValue);
self::assertNotInstanceOf(LazyLoadingInterface::class, $wrappedValue);
self::assertNotInstanceOf(ValueHolderInterface::class, $wrappedValue);
self::assertFalse($service->isProxyInitialized());
}

private function dumpLazyServiceProjectAsFilesServiceContainer()
Expand All @@ -104,6 +100,7 @@ private function dumpLazyServiceProjectAsFilesServiceContainer()
$container = new ContainerBuilder();

$container->register('foo', \stdClass::class)
->setProperty('bar', 123)
->setPublic(true)
->setLazy(true);
$container->compile();
Expand Down
6 changes: 3 additions & 3 deletions src/Symfony/Bridge/Doctrine/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@
"symfony/stopwatch": "^5.4|^6.0",
"symfony/cache": "^5.4|^6.0",
"symfony/config": "^5.4|^6.0",
"symfony/dependency-injection": "^5.4|^6.0",
"symfony/dependency-injection": "^6.2",
"symfony/form": "^5.4.9|^6.0.9",
"symfony/http-kernel": "^5.4|^6.0",
"symfony/messenger": "^5.4|^6.0",
"symfony/doctrine-messenger": "^5.4|^6.0",
"symfony/property-access": "^5.4|^6.0",
"symfony/property-info": "^5.4|^6.0",
"symfony/proxy-manager-bridge": "^5.4|^6.0",
"symfony/proxy-manager-bridge": "^6.2",
"symfony/security-core": "^6.0",
"symfony/expression-language": "^5.4|^6.0",
"symfony/uid": "^5.4|^6.0",
Expand All @@ -55,7 +55,7 @@
"doctrine/orm": "<2.7.4",
"phpunit/phpunit": "<5.4.3",
"symfony/cache": "<5.4",
"symfony/dependency-injection": "<5.4",
"symfony/dependency-injection": "<6.2",
"symfony/form": "<5.4",
"symfony/http-kernel": "<5.4",
"symfony/messenger": "<5.4",
Expand Down
29 changes: 26 additions & 3 deletions src/Symfony/Bridge/ProxyManager/Internal/ProxyGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Bridge\ProxyManager\Internal;

use Laminas\Code\Generator\ClassGenerator;
use ProxyManager\ProxyGenerator\LazyLoadingGhostGenerator;
use ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator;
use ProxyManager\ProxyGenerator\ProxyGeneratorInterface;
use Symfony\Component\DependencyInjection\Definition;
Expand All @@ -21,12 +22,22 @@
*/
class ProxyGenerator implements ProxyGeneratorInterface
{
private readonly ProxyGeneratorInterface $generator;

public function asGhostObject(bool $asGhostObject): static
{
$clone = clone $this;
$clone->generator = $asGhostObject ? new LazyLoadingGhostGenerator() : new LazyLoadingValueHolderGenerator();

return $clone;
}

/**
* {@inheritdoc}
*/
public function generate(\ReflectionClass $originalClass, ClassGenerator $classGenerator, array $proxyOptions = []): void
{
(new LazyLoadingValueHolderGenerator())->generate($originalClass, $classGenerator, $proxyOptions);
$this->generator->generate($originalClass, $classGenerator, $proxyOptions);

foreach ($classGenerator->getMethods() as $method) {
if (str_starts_with($originalClass->getFilename(), __FILE__)) {
Expand All @@ -41,18 +52,30 @@ public function generate(\ReflectionClass $originalClass, ClassGenerator $classG
}
}

public function getProxifiedClass(Definition $definition): ?string
public function getProxifiedClass(Definition $definition, bool &$asGhostObject = null): ?string
{
if (!$definition->hasTag('proxy')) {
if (!($class = $definition->getClass()) || !(class_exists($class) || interface_exists($class, false))) {
return null;
}

return (new \ReflectionClass($class))->name;
$class = new \ReflectionClass($class);
$name = $class->name;

if ($asGhostObject = !$class->isAbstract() && !$class->isInterface() && ('stdClass' === $class->name || !$class->isInternal())) {
while ($class = $class->getParentClass()) {
if (!$asGhostObject = 'stdClass' === $class->name || !$class->isInternal()) {
break;
}
}
}

return $name;
}
if (!$definition->isLazy()) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": setting the "proxy" tag on a service requires it to be "lazy".', $definition->getClass()));
}
$asGhostObject = false;
$tags = $definition->getTag('proxy');
if (!isset($tags[0]['interface'])) {
throw new \InvalidArgumentException(sprintf('Invalid definition for service of class "%s": the "interface" attribute is missing on the "proxy" tag.', $definition->getClass()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
namespace Symfony\Bridge\ProxyManager\LazyProxy\Instantiator;

use ProxyManager\Configuration;
use ProxyManager\Factory\LazyLoadingGhostFactory;
use ProxyManager\Factory\LazyLoadingValueHolderFactory;
use ProxyManager\GeneratorStrategy\EvaluatingGeneratorStrategy;
use ProxyManager\Proxy\GhostObjectInterface;
use ProxyManager\Proxy\LazyLoadingInterface;
use Symfony\Bridge\ProxyManager\Internal\LazyLoadingFactoryTrait;
use Symfony\Bridge\ProxyManager\Internal\ProxyGenerator;
Expand Down Expand Up @@ -43,18 +45,36 @@ public function __construct()
*/
public function instantiateProxy(ContainerInterface $container, Definition $definition, string $id, callable $realInstantiator): object
{
$proxifiedClass = new \ReflectionClass($this->generator->getProxifiedClass($definition));
$proxifiedClass = new \ReflectionClass($this->generator->getProxifiedClass($definition, $asGhostObject));
$generator = $this->generator->asGhostObject($asGhostObject);

$factory = new class($this->config, $this->generator) extends LazyLoadingValueHolderFactory {
use LazyLoadingFactoryTrait;
};
if ($asGhostObject) {
$factory = new class($this->config, $generator) extends LazyLoadingGhostFactory {
use LazyLoadingFactoryTrait;
};

$initializer = static function (&$wrappedInstance, LazyLoadingInterface $proxy) use ($realInstantiator) {
$wrappedInstance = $realInstantiator();
$proxy->setProxyInitializer(null);
$initializer = static function (GhostObjectInterface $proxy, string $method, array $parameters, &$initializer, array $properties) use ($realInstantiator) {
$instance = $realInstantiator($proxy);
$initializer = null;

return true;
};
if ($instance !== $proxy) {
throw new \LogicException(sprintf('A lazy initializer should return the ghost object proxy it was given as argument, but an instance of "%s" was returned.', get_debug_type($instance)));
}

return true;
};
} else {
$factory = new class($this->config, $generator) extends LazyLoadingValueHolderFactory {
use LazyLoadingFactoryTrait;
};

$initializer = static function (&$wrappedInstance, LazyLoadingInterface $proxy) use ($realInstantiator) {
$wrappedInstance = $realInstantiator();
$proxy->setProxyInitializer(null);

return true;
};
}

return $factory->createProxy($proxifiedClass->name, $initializer, [
'fluentSafe' => $definition->hasTag('proxy'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ public function __construct(string $salt = '')
*/
public function isProxyCandidate(Definition $definition, bool &$asGhostObject = null): bool
{
$asGhostObject = false;

return ($definition->isLazy() || $definition->hasTag('proxy')) && $this->proxyGenerator->getProxifiedClass($definition);
return ($definition->isLazy() || $definition->hasTag('proxy')) && $this->proxyGenerator->getProxifiedClass($definition, $asGhostObject);
}

/**
Expand All @@ -58,9 +56,30 @@ public function getProxyFactoryCode(Definition $definition, string $id, string $
$instantiation .= sprintf(' $this->%s[%s] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', var_export($id, true));
}

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

if ($asGhostObject) {
return <<<EOF
if (true === \$lazyLoad) {
$instantiation \$this->createProxy('$proxyClass', function () {
return \\$proxyClass::staticProxyConstructor(function (\ProxyManager\Proxy\GhostObjectInterface \$proxy, string \$method, array \$parameters, &\$initializer, array \$properties) {
\$instance = $factoryCode;
\$initializer = null;

if (\$instance !== \$proxy) {
throw new \LogicException(sprintf('A lazy initializer should return the ghost object proxy it was given as argument, but an instance of "%s" was returned.', get_debug_type(\$instance)));
}

return true;
});
});
}


EOF;
}

return <<<EOF
if (true === \$lazyLoad) {
$instantiation \$this->createProxy('$proxyClass', function () {
Expand Down Expand Up @@ -96,10 +115,10 @@ private function getProxyClassName(string $class): string

private function generateProxyClass(Definition $definition): ClassGenerator
{
$class = $this->proxyGenerator->getProxifiedClass($definition);
$class = $this->proxyGenerator->getProxifiedClass($definition, $asGhostObject);
$generatedClass = new ClassGenerator($this->getProxyClassName($class));

$this->proxyGenerator->generate(new \ReflectionClass($class), $generatedClass, [
$this->proxyGenerator->asGhostObject($asGhostObject)->generate(new \ReflectionClass($class), $generatedClass, [
'fluentSafe' => $definition->hasTag('proxy'),
'skipDestructor' => true,
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
require_once __DIR__.'/Fixtures/includes/foo.php';

use PHPUnit\Framework\TestCase;
use ProxyManager\Proxy\LazyLoadingInterface;
use ProxyManager\Proxy\GhostObjectInterface;
use ProxyManagerBridgeFooClass;
use Symfony\Bridge\ProxyManager\LazyProxy\Instantiator\RuntimeInstantiator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
Expand All @@ -38,23 +38,21 @@ public function testCreateProxyServiceWithRuntimeInstantiator()

$builder->compile();

/* @var $foo1 \ProxyManager\Proxy\LazyLoadingInterface|\ProxyManager\Proxy\ValueHolderInterface */
/* @var $foo1 \ProxyManager\Proxy\GhostObjectInterface */
$foo1 = $builder->get('foo1');

$foo1->__destruct();
$this->assertSame(0, $foo1::$destructorCount);

$this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved on multiple subsequent calls');
$this->assertInstanceOf(ProxyManagerBridgeFooClass::class, $foo1);
$this->assertInstanceOf(LazyLoadingInterface::class, $foo1);
$this->assertInstanceOf(GhostObjectInterface::class, $foo1);
$this->assertFalse($foo1->isProxyInitialized());

$foo1->initializeProxy();

$this->assertSame($foo1, $builder->get('foo1'), 'The same proxy is retrieved after initialization');
$this->assertTrue($foo1->isProxyInitialized());
$this->assertInstanceOf(ProxyManagerBridgeFooClass::class, $foo1->getWrappedValueHolderValue());
$this->assertNotInstanceOf(LazyLoadingInterface::class, $foo1->getWrappedValueHolderValue());

$foo1->__destruct();
$this->assertSame(1, $foo1::$destructorCount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
namespace Symfony\Bridge\ProxyManager\Tests\LazyProxy\Dumper;

use PHPUnit\Framework\TestCase;
use ProxyManager\Proxy\LazyLoadingInterface;
use ProxyManager\Proxy\GhostObjectInterface;
use Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\ProxyDumper;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
Expand Down Expand Up @@ -47,7 +47,7 @@ public function testDumpContainerWithProxyServiceWillShareProxies()

$proxy = $container->get('foo');
$this->assertInstanceOf(\stdClass::class, $proxy);
$this->assertInstanceOf(LazyLoadingInterface::class, $proxy);
$this->assertInstanceOf(GhostObjectInterface::class, $proxy);
$this->assertSame($proxy, $container->get('foo'));

$this->assertFalse($proxy->isProxyInitialized());
Expand All @@ -62,8 +62,10 @@ private function dumpLazyServiceProjectServiceContainer()
{
$container = new ContainerBuilder();

$container->register('foo', 'stdClass')->setPublic(true);
$container->getDefinition('foo')->setLazy(true);
$container->register('foo', 'stdClass')
->setPublic(true)
->setLazy(true)
->setProperty('bar', 123);
$container->compile();

$dumper = new PhpDumper($container);
Expand Down
Loading