Ad

Use Laravel's Container Outside Of Laravel

- 1 answer

Why?

  1. I'm trying to use a few other Laravel pieces like Pipeline in a standalone library, which requires Container.
  2. Using Container to make() classes is addicting, I want the auto constructor dependency handling (assuming concrete, typehinted dependencies).

So I wrote a helper method:

function container()
{
  if(is_null(Container::getInstance())) {
      Container::setInstance(new Container());
  }
  return Container::getInstance();
}

I didn't want to conflict with any existing helper methods if this library was being used inside Laravel. And by checking for an existing static instance, I think this will play nicely inside or outside Laravel.

And this works! I can do container()->make(SomeClass::class) and it will automatically build and inject constructor dependencies.

Mostly.

If that class has a dependency for the Container itself (like Pipeline does), then it barfs:

BindingResolutionException: Target [Illuminate\Contracts\Container\Container] is not instantiable

Sure, ok, the Pipeline is requiring a contract, which isn't wired up. So let's update the helper method to do just that:

function container()
{
    if(is_null(Container::getInstance())) {
        $container = new Container();
        $container->bind('Illuminate\Contracts\Container\Container', $container);
        Container::setInstance($container);
    }

    return Container::getInstance();
}

But now I'm getting:

Illegal offset type in isset or empty

And the stack trace showing a bunch of line numbers from Container.php.

Any idea how I might wire up Container manually, outside of Laravel, such that I can then bind() things, and use Container to build classes and handle dependencies including itself?

Ad

Answer

Since you're binding to an existing object, use the instance method:

$container->instance('Illuminate\Contracts\Container\Container', $container);
Ad
source: stackoverflow.com
Ad