symfony-docs icon indicating copy to clipboard operation
symfony-docs copied to clipboard

Clarify Lazy Services usage with `final` & `readonly` classes

Open kiler129 opened this issue 6 months ago • 0 comments

Since Symfony 7.3 lazy services support final and readonly objects:

% grep TaskGroups src/UseCase/CreateUser.php 
final class TaskGroups extends YamlConfig
% bin/console debug:container 'App\UseCase\CreateUser' 2>/dev/null | grep Lazy
  Lazy             yes

This works since PHP 8.4 allows for native lazy ghosts that don't need to extend the class:

final readonly class TestObject {
    public function __construct(public int $number) {
        echo "Constructor called\n";
    }

    public function getLucky(): void {
        echo "Your lucky number: $this->number\n";
    }
}

$lazy = new ReflectionClass(TestObject::class)->newLazyGhost(function (TestObject $object) {
    $object->__construct(\random_int(0, 100));
});
echo "Object created\n";
$lazy->getLucky();

The support for this feature was introduced in https://github.com/symfony/symfony/commit/ed695a64df11f30610479c1c7555b75bd795ea3d (precisely here). However, documentation still points users to use Interface Proxifying, regardless of the frameworks or PHP version.

kiler129 avatar Jun 07 '25 04:06 kiler129