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] Adds a new "Alias" contextual attribute #54898

Closed
wants to merge 2 commits into from

Conversation

hijhem
Copy link

@hijhem hijhem commented Mar 4, 2025

Motivation

Laravel provides a way to define an alias when registering a service in the container, which is convenient when initializing a subset of the service and using it in different parts of the application.

// Service
class State
{
    public function __construct(private string $storageKey) {}
}

// AppServiceProvider
$this->app->bind('module1.state', fn () => new State('module1'));
$this->app->bind('module2.state', fn () => new State('module2'));

However, there is no straightforward way to inject these instances into multiple services without manually binding them in the service provider.

Solution

A new Alias contextual attribute allows dependencies to be resolved by their alias.

class Service
{
    public function __construct(private #[Alias('module1.state')] State $state) {}
}

This ensures that the correct instance of State is resolved based on the specified alias.

@henzeb
Copy link
Contributor

henzeb commented Mar 4, 2025

maybe we can do something with abstract? just like the method parameter is named? I don' t know, Alias feels confusing as it is also used for aliassing classes like the facades.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

@hijhem hijhem deleted the alias-contextual-attribute branch March 5, 2025 17:06
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.

3 participants