Tuesday, May 23, 2017

Dependency resolving with make not working when bind is done by a provider in Laravel

I'm using Laravel 5.2. I tried to resolve a dependency in laravel out of the IOCContainer as follows.(with App::make method)

App/FooController.php:-

<?php

namespace App\Http\Controllers;

use App\Bind\FooInterface;
use Illuminate\Support\Facades\App;

class FooController extends Controller
{
    public  function outOfContainer(){
        dd(App::make('\App\bind\FooInterface')); // Focus: program dies here!!
    }
}

Bindings for the FooInterface done in the AppServiceProvider as follows

App/Providers/AppServiceProvider.php:-

<?php

namespace App\Providers;

use App\Bind\Foo;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('\App\Bind\FooInterface', function() {
            return new Foo();
        });
    }
}

Structure of the Foo class as follows.

App/Bind/Foo.php:-

<?php

namespace App\Bind;


class Foo implements FooInterface {

} 

Structure of the 'FooInterface' interface as follows:-

<?php

namespace App\Bind;


interface FooInterface {

}

Then I created a routed as follows.

Route::get('/outofcontainer', 'FooController@outOfContainer');

But when I browse this route it throws an exception in informing,

BindingResolutionException in Container.php line 748:
Target [App\bind\FooInterface] is not instantiable.

What is going wrong with this? How to use App:make() with the AppServiceProvider?



via user8057101

Advertisement