Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Laravel's Container outside of Laravel

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?

like image 653
jszobody Avatar asked Oct 19 '22 17:10

jszobody


1 Answers

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

$container->instance('Illuminate\Contracts\Container\Container', $container);
like image 179
Joseph Silber Avatar answered Oct 22 '22 01:10

Joseph Silber