Skip to content
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

[12.x] Bind abstract from concrete's return type #54628

Merged
merged 2 commits into from
Feb 17, 2025

Conversation

peterfox
Copy link
Contributor

@peterfox peterfox commented Feb 15, 2025

Changes

  • Updates the params for the container contract and implementation
  • Adds the closureReturnTypes method to the Container
  • changes the container's bind method to allow a Closure in the abstract parameter and process the closure's return types to call bind
  • Adds a test covering the bind and singleton methods to show they work.

Why

I thought this would be a cool thing to use when it comes to the container, I've had it in mind for a while. It follows the same idea as how some test assertion methods use reflection to know what events/jobs etc to expect. Instead this looks at the return type for the concrete Closures for the container.

TDLR; You would be able to provide a type hinted closure and it would use the return type to assign the abstract rather than specifying it with a string.

Example code:

$this->bind(function (): \FooContract {
     return new FooInstance();
});

This would allow you to also handle multiple contracts with one Closure:

$this->bind(function (): \FooContract|\BarContract {
     return new FooAndBarInstance();
});

This could also lead to some future benefits where the container can be more transparent about what abstracts will return without having to call the closure itself.

Notes

Mainly a proof of concept PR, happy to clean up and add additional tests where there might be additional edge cases.

I've added this to Laravel 12. Nothing stopping it going to Laravel 11 but it feels like something to launch with a new version.

@taylorotwell taylorotwell merged commit 834cf27 into laravel:master Feb 17, 2025
39 checks passed
@taylorotwell
Copy link
Member

Nice - thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants