Skip to content

[Laravel] Auto-Configuration Instantiates Dependencies Too Early #7033

@cay89

Description

@cay89

API Platform version(s) affected: 4.1.1

It's probably because of "auto configure our tagged interfaces" that I'm encountering an issue where, if I pass a dependency to a ProcessorInterface-implementing class via the constructor—one that I configure in my own AppServiceProvider—it results in an error. This happens because it tries to instantiate the class before my AppServiceProvider runs.

This is how it looks:

class MyDependency
{
    public function __construct(
        private readonly string $param,
    ) {
    }
}
class ExampleProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly MyDependency $dependency,
    ) {
    }
    
    public function process(
        mixed $data,
        Operation $operation,
        array $uriVariables = [],
        array $context = [],
    ) {
        // do something with $this->dependency
    }
}
class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(
            MyDependency::class,
            fn() => new MyDependency(
                config('my_dependency.param'),
            ),
        );
    }
}

So this is now causing an error like this:

PHP Fatal error: Uncaught Illuminate\Contracts\Container\BindingResolutionException: Unresolvable dependency resolving [...] in class ... in /app/vendor/laravel/framework/src/Illuminate/Container/Container.php:1231

I would also be fine with keeping the previous approach somehow, where I manually register my ProcessorInterface / ProviderInterface classes in my own AppServiceProvider, as that previously worked:

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(
            MyDependency::class,
            fn() => new MyDependency(
                config('my_dependency.param'),
            ),
        );
        $this->app->tag([ExampleProcessor::class], ProcessorInterface::class);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions