Skip to content

Cannot fake primitive bindings using config #38893

Closed
@ol1s

Description

@ol1s

Description:

  • Laravel Version: 8.50.0
  • PHP Version: 7.4.23
  • Database Driver & Version:

When I bind a primitive to a class using a config value I cannot override this in my feature tests

Steps To Reproduce:

Setup primitive bindings in container:

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->when(ExampleService::class)
            ->needs('$baseUrl')
            ->give(config('services.example.host'));
    }
}

Inject bindings into constructor:

class ExampleService
{
    public function __construct(string $baseUrl)
    {
    }
}

Override (fake) the config value in feature test:

class ExampleFeatureTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();
        config()->set('services.example.host', 'http://test');
    }
}

Result

The value of the config('services.example.host') passed to the primitive binding $baseUrl in ExampleService remains as it was at boot-time (ie. null)

BindingResolutionException(code: 0): Unresolvable dependency resolving [Parameter #0 [ <required> string $baseUrl ]]
in class App\\Services\\ExampleService at vendor/laravel/framework/src/Illuminate/Container/Container.php:1104)

Expected

The value of config('services.example.host') injected from the container should instead be http://test

Workaround

I had to abandon contextual binding and instead decorate my class using setter as follows:

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->extend(ExampleService::class, function ($class) {
            return $class->setBaseUrl(config('services.example.host'));
        });
    }
}
class ExampleService
{
    public function setBaseUrl(string $baseUrl): self
    {
        //etc
        return $this;
    }
}

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