Added explicitly lazy construct method.
This commit is contained in:
parent
7096db3114
commit
8b7b4cf73a
2 changed files with 31 additions and 2 deletions
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
|||
0.2501.221039
|
||||
0.2501.221237
|
||||
|
|
|
@ -87,6 +87,35 @@ class Dependencies {
|
|||
return $objInfo->newInstanceArgs($this->resolveArgs($constructor, $args));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an object using dependencies and delays construction.
|
||||
*
|
||||
* @template T of object
|
||||
* @param class-string<T> $class Class string.
|
||||
* @param mixed ...$args Arguments to be passed to the constructor.
|
||||
* @return T
|
||||
*/
|
||||
public function constructLazy(string $class, mixed ...$args): object {
|
||||
$objInfo = new ReflectionClass($class);
|
||||
if(!$objInfo->isInstantiable())
|
||||
throw new InvalidArgumentException('$class must be instantiable');
|
||||
|
||||
return $objInfo->newLazyGhost(function(object $object) use ($objInfo, $args) {
|
||||
try {
|
||||
$constructor = $objInfo->getMethod('__construct');
|
||||
} catch(ReflectionException $ex) {
|
||||
return;
|
||||
}
|
||||
|
||||
if(!$constructor->isPublic())
|
||||
throw new RuntimeException(sprintf('constructor of %s is not public', $objInfo->getName()));
|
||||
if(!$constructor->isConstructor())
|
||||
throw new RuntimeException(sprintf('__construct on %s is not not a constructor somehow', $objInfo->getName()));
|
||||
|
||||
$constructor->invokeArgs($object, $this->resolveArgs($constructor, $args));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a dependency class. Use a class string and $args to create lazy object.
|
||||
*
|
||||
|
@ -194,7 +223,7 @@ class Dependencies {
|
|||
return [];
|
||||
|
||||
if($predicate === null)
|
||||
return $this->objects[$class];
|
||||
return $this->objects[$class]; // @phpstan-ignore-line: trust me
|
||||
|
||||
return XArray::where($this->objects[$class], $predicate); // @phpstan-ignore-line: this is fine
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue