Skip to content

Commit

Permalink
creating lazy services in PHP 8.4 WIP
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Nov 25, 2024
1 parent 9b9bfb4 commit 1e641d6
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/DI/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ class Container
/** @var array[] type => (high, low, no) => services */
protected array $wiring = [];

/** @var string[] service name => class */
protected array $lazy = [];

/** @var object[] service name => instance */
private array $instances = [];

Expand Down Expand Up @@ -215,7 +218,9 @@ public function createService(string $name): object
if ($callback = ($this->factories[$name] ?? null)) {
$service = $this->preventDeadLock($name, fn() => $callback());
} elseif (isset($this->methods[$method])) {
$service = $this->preventDeadLock($name, fn() => $this->$method());
$service = isset($this->lazy[$name])
? (new \ReflectionClass($this->lazy[$name]))->newLazyProxy($this->$method(...))
: $this->preventDeadLock($name, fn() => $this->$method());
} else {
throw new MissingServiceException(sprintf("Service '%s' not found.", $name));
}
Expand Down
28 changes: 28 additions & 0 deletions src/DI/Extensions/DIExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
namespace Nette\DI\Extensions;

use Nette;
use Nette\DI\Definitions\ServiceDefinition;
use Nette\PhpGenerator as Php;
use Tracy;


Expand All @@ -36,6 +38,7 @@ public function __construct(bool $debugMode = false)
public array $excluded = [];
public ?string $parentClass = null;
public object $export;
public bool $lazy = false;
};
$this->config->export = new class {
public bool $parameters = true;
Expand All @@ -62,6 +65,7 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class): void
$class->setExtends($this->config->parentClass);
}

$this->initializeLazy($class);
$this->restrictParameters($class);
$this->restrictTags($class);
$this->restrictTypes($class);
Expand All @@ -75,6 +79,30 @@ public function afterCompile(Nette\PhpGenerator\ClassType $class): void
}


private function initializeLazy(Nette\PhpGenerator\ClassType $class): void
{
if (!$this->config->lazy || PHP_VERSION_ID < 80400) {
return;
}

$classes = [];
foreach ($this->getContainerBuilder()->getDefinitions() as $name => $def) {
if ($def instanceof ServiceDefinition
&& is_string($def->getEntity())
&& ($rc = new \ReflectionClass($def->getEntity()))
&& !$rc->isInternal()
) {
$classes[$name] = $rc->getName();
}
}

(new Php\ClassManipulator($class))
->inheritProperty('lazy')
->setComment(null)
->setValue($classes);
}


private function restrictParameters(Nette\PhpGenerator\ClassType $class): void
{
if (!$this->config->export->parameters) {
Expand Down

0 comments on commit 1e641d6

Please sign in to comment.