2

I want to fire one of my Service Provider (and its bindings) just when (and only when) another given class will have own object. In another words: I want to pass Service Provider to object by Dependency injection like this:

class ExampleController extends Controller {

    public function __construct(TestServiceProvider $testServiceProvider) {

        // here I want to fire register method of testServiceProvider

    }

But then I got error:

Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Support\ServiceProvider

Is that possible? I just want to have a control when Service Provider is fired.

Thanks in advance.

Adam Kozlowski
  • 5,606
  • 2
  • 32
  • 51

1 Answers1

0

I think you should not pass service providers like this, but instead defer the Service Provider itself:

If your provider is only registering bindings in the service container, you may choose to defer its registration until one of the registered bindings is actually needed. Deferring the loading of such a provider will improve the performance of your application, since it is not loaded from the filesystem on every request.

Laravel compiles and stores a list of all of the services supplied by deferred service providers, along with the name of its service provider class. Then, only when you attempt to resolve one of these services does Laravel load the service provider.

— Quote from Laravel documentation

In the documentation page you can also find a small example and how to defer a service provider

mdexp
  • 3,492
  • 2
  • 9
  • 20