Skip to content

Freeze #[Immutable] services registered with a closure or instance() - #370

Merged
techmahedy merged 1 commit into
doppar:4.xfrom
techmahedy:issue-4.x
Oct 17, 2026
Merged

techmahedy merged 1 commit into
doppar:4.xfrom
techmahedy:issue-4.x

Conversation

@techmahedy

@techmahedy techmahedy commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Pull Request Checklist

Q A
Branch? 4.x
Bug fix? yes
New feature? yes
Deprecations? no
Issues -
License MIT

Description

A service marked #[Immutable] was only frozen when the container built it itself. If you created the object in a launcher and handed it to the container, it was never frozen, even though the docs showed exactly that pattern and promised it would be. This PR makes the container freeze these services the first time it resolves them, whichever way they were registered.

The problem

The docs teach this launcher pattern:

$payment = new PaymentService();
$payment->gateway = config('payment.gateway');

$this->app->singleton(PaymentService::class, fn () => $payment);

The service never froze. isFrozen() returned false and writes like $payment->taxRate = 0.0 were allowed, anywhere in the app. The same was true for $this->app->instance(PaymentService::class, $payment).

The reason is that freeze() was only called from Container::build(). A closure binding or instance() never goes through build(), so nothing froze the object. The only forms that worked were no registration at all, singleton(PaymentService::class) with no closure, or a closure that called $app->build(...). People following the docs got a service that looked protected and was not.

Behavior change to know about

An app that registered an #[Immutable] service through a closure or instance() and then changed it after the first resolve will now get an ImmutableViolationException. The docs always promised that this would happen, so I treat it as a bug fix, but it is worth a line in the release notes.

Checklist

  • Tests have been added or updated
  • Documentation has been updated if necessary
  • Code follows the project coding standards
  • All tests pass locally

@techmahedy techmahedy added bug Something isn't working feat new feature labels Oct 17, 2026
@techmahedy
techmahedy merged commit e56a8e7 into doppar:4.x Oct 17, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working feat new feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant