Skip to content

Clarify Lazy Services usage with final & readonly classes #21065

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 1 commit into
base: 7.3
Choose a base branch
from

Conversation

kiler129
Copy link
Contributor

@kiler129 kiler129 commented Jun 7, 2025

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 symfony/symfony@ed695a6 (precisely here). However, documentation still points users to use Interface Proxifying, regardless of the frameworks or PHP version.

@@ -23,8 +23,8 @@ until you interact with the proxy in some way.

.. warning::

Lazy services do not support `final`_ or ``readonly`` classes, but you can use
`Interface Proxifying`_ to work around this limitation.
Lazy services support for `final`_ or ``readonly`` classes was introduced in Symfony 7.3, and
Copy link
Contributor

Choose a reason for hiding this comment

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

This is not a warning anymore, make let's move this to a versionadded 7.3 directive?

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants