How do I use Laravel's service container in a package (outside of an app)?

Viewed 709

I'm developing a package, which can be consumed by Laravel applications. The package has a ServiceProvider, which consumers use when they want to instantiate stuff from the package.

Now, I would like to use this ServiceProvider in the package's own tests to resolve dependencies. Integration testing if you will.

How can I do that?

It looks like resolve() depends on app(), so am I correct in assuming that the Laravel service container is not standalone and can only be used inside of an application?

1 Answers

tldr; composer require illuminate/container

The App:: facade resolves to Illuminate\Foundation\Application::class, and the helper functions (including app()) are found in the same namespace. So you'd need to composer require illuminate/foundation to get this.

However, the actual container is at Illuminate\Container\Container - this is the base class which is extended by the Application class above, so you could get a thinned-down version of just the container with composer require illuminate/container.

I should also note that they appear to share the same static::$instance so using the illuminate container should work in both Laravel and non-Laravel apps.

Example resolving an instance, and calling a method with automatic dependency injection:

use Illuminate\Container\Container;

$container = Container::getInstance();
$concrete = $container->make(Some\Abstract\Interface::class);
$result = $container->call([$concrete, 'methodWithDependencies']);
Related