Skip to content

[13.x] Add a #[BindWhen()] attribute to conditionally bind into the container#60862

Open
ziadoz wants to merge 14 commits into
laravel:13.xfrom
ziadoz:feature/bind-when-attribute
Open

[13.x] Add a #[BindWhen()] attribute to conditionally bind into the container#60862
ziadoz wants to merge 14 commits into
laravel:13.xfrom
ziadoz:feature/bind-when-attribute

Conversation

@ziadoz

@ziadoz ziadoz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

This adds a new #[BindWhen] attribute, which makes it possible to do things that #[Bind] can't, since it's restricted to filtering environments. It relies on PHP 8.5, which allows static closures as attribute parameters.

My use case is wanting to load different services and features for specific customers depending on configuration. The closure receives the container though, so it could be used for more complex binding scenarios.

  #[BindWhen(BetaPaymentGateway::class, static function ($container) {
      return $container->make('config')->get('features.payments.beta');
  })]
  #[Bind(FakePaymentGateway::class, environments: ['local', 'testing'])]
  #[Bind(StripePaymentGateway::class)]
  interface PaymentGatewayInterface {}

The attributes are still processed in the order they're defined in the code:

// Assuming the environment is production:
#[BindWhen(A::class, static fn () => false)]  // skipped
#[Bind(B::class)]                             // skipped
#[BindWhen(C::class, static fn () => true)]   // bound
#[Bind(D::class, 'local')]                    // skipped

Note: The failing DB tests aren't related as far as I can tell.

@github-actions

Copy link
Copy Markdown

Thanks for submitting a PR!

Note that draft PRs 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.

@Lukasss93

Copy link
Copy Markdown
Contributor

Nice idea!
It would also be cool to have a cleaner shortcut, for example:

#[BindWhenConfig(BetaPaymentGateway::class, 'features.payments.beta')]   // <-- must be boolean

@shaedrich

Copy link
Copy Markdown
Contributor

Have you considered to add the second parameter directly to #[Bind]?

@ziadoz

ziadoz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Have you considered to add the second parameter directly to #[Bind]?

@shaedrich I did consider it, but it didn't seem ideal having to either specify the environments parameter default ['*'], or use a named when parameter. A new attribute seemed simpler.

@ziadoz
ziadoz marked this pull request as ready for review July 22, 2026 15:36
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