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

[11.x] Allow for contextual bindings using attributes #51115

Draft
wants to merge 1 commit into
base: 11.x
Choose a base branch
from

Conversation

ollieread
Copy link
Contributor

@ollieread ollieread commented Apr 18, 2024

Note

I will update this with tests and some default implementations before marking for review. I've created it as a draft PR in case anyone wishes to feedback.

This PR adds functionality to allow users to register PHP 8 attributes and associated handlers with the container to add in resolving dependencies. All attributes must implement the Illuminate\Contracts\Container\ContextualAttribute marker interface. The attributes should be added to parameters, and will trump normal resolution.

The primary use of this sort of functionality would be to have dependency injection work with auth guards, connections, and other things where multiple instances exist with no difference from the perspective of the container.

Let's say for example that you have a platform that uses two guards, and different classes depend on different ones. Currently, the only solution to this is to manually get the guard, or create a contextual binding for each class. Instead, you could achieve it like so.

First, you create the attribute.

#[Attribute(Attribute::TARGET_PARAMETER)]
class AuthGuard implements ContextualAttribute
{
	public function __construct(
		public readonly string $name
	){}
}

Then you register it with the container.

Container::getInstance()->whenHas(AuthGuard::class, function (AuthGuard $attribute) {
	return Auth::guard($attribute->name);
});

Once this is done, you can use the attribute with dependency injection.

class MyService {
	private Guard $guard;
	
	public function __construct(#[AuthGuard('api')] Guard $guard) {
		$this->guard = $guard;
	}
}

$service = Container::getInstance()->make(MyService::class);

Copy link

Thanks for submitting a PR!

Note that draft PR's are not reviewed. If you would like a review, please mark your pull request as ready for review in the GitHub user interface.

Pull requests that are abandoned in draft may be closed due to inactivity.

@driesvints driesvints changed the title Allow for contextual bindings using attributes [11.x] Allow for contextual bindings using attributes Apr 18, 2024
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.

None yet

1 participant