Skip to content

Contextual binding does not work #21300

Closed
@iamlucianojr

Description

@iamlucianojr
  • Laravel Version: 5.5.9
  • PHP Version: 7.1.4
  • Database Driver & Version: Mysql 8.0

Description:

When you use contextual binding to resolve class dependencies in controllers you got the error:

[Illuminate\Contracts\Container\BindingResolutionException]  
  Target [App\Core\Contracts\RepositoryInterface] is not in    
  stantiable while building [\App\Domains\Brands\Controller    
  s\BrandsController].

Steps To Reproduce:

  • I have created a controller that depends of RepositoryInterface;

  • Create the RepositoryInterface;

  • Create BrandsRepository that implements the RepositoryInterface

namespace App\Domains\Brands\Controllers;
class BrandsController extends Controller
{
    public function __construct(RepositoryInterface $repository) {}
}

namespace App\Core\Contracts;
interface RepositoryInterface {}

namespace App\Domains\Brands\Repositories;
class BrandsRepository implements RepositoryInterface {}

In my service provider I have:

namespace App\Domains\Brands\Providers;

use App\Core\Contracts\RepositoryInterface;
use App\Domains\Brands\Controllers\BrandsController;
use App\Domains\Brands\Repositories\BrandsRepository;
use Illuminate\Support\ServiceProvider;

class BrandsServiceProvider extends ServiceProvider
{
     /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->when(BrandsController::class)
            ->needs(RepositoryInterface::class)
            ->give(BrandsRepository::class);
    }
}

If I directly bind the repository it works, like this:

namespace App\Domains\Brands\Providers;

use App\Core\Contracts\RepositoryInterface;
use App\Domains\Brands\Controllers\BrandsController;
use App\Domains\Brands\Repositories\BrandsRepository;
use Illuminate\Support\ServiceProvider;

class BrandsServiceProvider extends ServiceProvider
{
     /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind(RepositoryInterface::class, BrandsRepository::class);
    }
}

But of course it is not what I want, because in my others controllers domains, like customers, I will receive the BrandsRepository instead CustomersRepository for example.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions