Skip to content

[13.x] RFC: Lazy Services - New #[Lazy] Attribute #55645

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

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
}
],
"require": {
"php": "^8.3",
"php": "^8.4",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Laravel 13 will depends on PHP 8.3 as minimum.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alrighty, in that case we can consider version 14.x, but any potential merging should wait until 13.x is released - is that correct? :)

"ext-ctype": "*",
"ext-filter": "*",
"ext-hash": "*",
Expand Down
11 changes: 11 additions & 0 deletions src/Illuminate/Container/Attributes/Lazy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace Illuminate\Container\Attributes;

use Attribute;

#[Attribute]
class Lazy
{
//
}
45 changes: 38 additions & 7 deletions src/Illuminate/Container/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use ArrayAccess;
use Closure;
use Exception;
use Illuminate\Container\Attributes\Lazy;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Contracts\Container\CircularDependencyException;
use Illuminate\Contracts\Container\Container as ContainerContract;
Expand Down Expand Up @@ -812,13 +813,14 @@ public function makeWith($abstract, array $parameters = [])
*
* @param string|class-string<TClass> $abstract
* @param array $parameters
* @param ReflectionAttribute<TClass>[] $attributes
* @return ($abstract is class-string<TClass> ? TClass : mixed)
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
*/
public function make($abstract, array $parameters = [])
public function make($abstract, array $parameters = [], array $attributes = [])
{
return $this->resolve($abstract, $parameters);
return $this->resolve($abstract, $parameters, attributes: $attributes);
}

/**
Expand Down Expand Up @@ -850,12 +852,14 @@ public function get(string $id)
* @param string|class-string<TClass>|callable $abstract
* @param array $parameters
* @param bool $raiseEvents
* @param ReflectionAttribute<TClass>[] $attributes
*
* @return ($abstract is class-string<TClass> ? TClass : mixed)
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Illuminate\Contracts\Container\CircularDependencyException
*/
protected function resolve($abstract, $parameters = [], $raiseEvents = true)
protected function resolve($abstract, $parameters = [], $raiseEvents = true, array $attributes = [])
{
$abstract = $this->getAlias($abstract);

Expand Down Expand Up @@ -887,7 +891,7 @@ protected function resolve($abstract, $parameters = [], $raiseEvents = true)
// the binding. This will instantiate the types, as well as resolve any of
// its "nested" dependencies recursively until all have gotten resolved.
$object = $this->isBuildable($concrete, $abstract)
? $this->build($concrete)
? $this->build($concrete, $attributes)
: $this->make($concrete);

// If we defined any extenders for this type, we'll need to spin through them
Expand Down Expand Up @@ -993,12 +997,13 @@ protected function isBuildable($concrete, $abstract)
* @template TClass of object
*
* @param \Closure(static, array): TClass|class-string<TClass> $concrete
* @param ReflectionAttribute<TClass>[] $attributes
* @return TClass
*
* @throws \Illuminate\Contracts\Container\BindingResolutionException
* @throws \Illuminate\Contracts\Container\CircularDependencyException
*/
public function build($concrete)
public function build($concrete, array $attributes = [])
{
// If the concrete type is actually a Closure, we will just execute it and
// hand back the results of the functions, which allows functions to be
Expand Down Expand Up @@ -1058,13 +1063,39 @@ public function build($concrete)

array_pop($this->buildStack);

$isLazy = $this->isLazy(array_merge($attributes, $reflector->getAttributes(Lazy::class)));

if ($isLazy) {
$instance = $reflector->newLazyProxy(function () use ($concrete, $instances) {
return new $concrete(...$instances);
});
Comment on lines +1069 to +1071
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could do just

Suggested change
$instance = $reflector->newLazyProxy(function () use ($concrete, $instances) {
return new $concrete(...$instances);
});
$instance = $reflector->newLazyProxy(fn () => new $concrete(...$instances));

} else {
$instance = $reflector->newInstanceArgs($instances);
}

$this->fireAfterResolvingAttributeCallbacks(
$reflector->getAttributes(), $instance = $reflector->newInstanceArgs($instances)
$reflector->getAttributes(), $instance
);

return $instance;
}

/**
* @template TClass of object
*
* @param ReflectionAttribute<TClass>[] $attributes
*
* @return bool
*/
protected function isLazy(array $attributes): bool
{
if (empty($attributes)) {
return false;
}

return array_any($attributes, static fn($attribute) => $attribute->getName() === Lazy::class);
}

/**
* Resolve all of the dependencies from the ReflectionParameters.
*
Expand Down Expand Up @@ -1199,7 +1230,7 @@ protected function resolveClass(ReflectionParameter $parameter)
try {
return $parameter->isVariadic()
? $this->resolveVariadicClass($parameter)
: $this->make($className);
: $this->make($className, $parameter->getAttributes(), $parameter->getAttributes());
}

// If we can not resolve the class instance, we will check to see if the value
Expand Down
146 changes: 146 additions & 0 deletions tests/Container/ContainerLazyTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
<?php

namespace Illuminate\Tests\Container;

use Illuminate\Container\Attributes\Lazy;
use Illuminate\Container\Container;
use PHPUnit\Framework\TestCase;

class ContainerLazyTest extends TestCase
{
protected function tearDown(): void
{
Container::setInstance();
}

public function testConcreteDoesNotThrowsExceptionWithAttribute()
{
$container = new Container;
$lazy = $container->make(LazyWithAttributeStub::class);

// No RuntimeException has occurred
// LazyWithAttributeStub behaves like a Lazy Object, but this is not obvious from its type
$this->assertInstanceOf(LazyWithAttributeStub::class, $lazy);
}

public function testConcreteThrowsExceptionWithoutAttribute()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Lazy call');

$container = new Container;
$container->make(LazyWithoutAttributeStub::class);
}

public function testConcreteDoesNotThrowsExceptionWithNoLogicConstructor()
{
$container = new Container;
$lazy = $container->make(LazyWithAttributeStub::class);

$this->assertInstanceOf(LazyWithAttributeStub::class, $lazy);

$this->assertSame('work', $lazy->work());
}

public function testConcreteDoesThrowsExceptionWithConstructorWithLogic()
{
$container = new Container;
$lazy = $container->make(LazyWithAttributeLogicStub::class);

// No RuntimeException has occurred so far
$this->assertInstanceOf(LazyWithAttributeLogicStub::class, $lazy);

$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Lazy call');

// Only the call to number() causes a RuntimeException
$lazy->number();
}

public function testConcreteThrowsExceptionButNotLazyDependency()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Parent call');

$container = new Container;
$container->make(LazyDependencyWithAttributeStub::class);
}

public function testConcreteNotLazyDependencyThrowsException()
{
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('Lazy call');

$container = new Container;
$container->make(LazyDependencyWithoutAttributeStub::class);
}
}

#[Lazy]
class LazyWithAttributeStub
{
public function __construct()
{
throw new \RuntimeException('Lazy call');
}

public function work()
{
return 'work';
}
}

class LazyWithTestRenameAttributeStub
{
public function __construct()
{
throw new \RuntimeException('Lazy call');
}

public function work()
{
return 'work';
}
}

#[Lazy]
class LazyWithAttributeLogicStub
{
public $number;

public function __construct()
{
$this->number = 10;

throw new \RuntimeException('Lazy call');
}

public function number()
{
$this->number += 10;
}
}

class LazyWithoutAttributeStub
{
public function __construct()
{
throw new \RuntimeException('Lazy call');
}
}

class LazyDependencyWithAttributeStub
{
public function __construct(#[Lazy] LazyWithTestRenameAttributeStub $stub)
{
throw new \RuntimeException('Parent call');
}
}

class LazyDependencyWithoutAttributeStub
{
public function __construct(LazyWithoutAttributeStub $stub)
{
throw new \RuntimeException('Parent call');
}
}
Loading