Laravel 5 - Interface is not instantiable

2019-02-02 20:09发布

I know that this question was asked so many times, but none of answers helped me.

I'm getting exception in Laravel 5

BindingResolutionException in Container.php line 785:
Target [App\Contracts\CustomModelInterface] is not instantiable.

What I've done without success:

  • Register App\Providers\AppRepositoryProvider in app.php providers
  • php artisan clear-compiled
  • Everything works if I replace interfaces on repositories in MyService, but I feel that it's wrong (should it be handled by IoC container?).

Structure:

app
  - Contracts
    - CustomModelInterface.php
  - Models
    - CustomModel.php
  - Repositories
    - CustomModelRepository.php
  - Providers
    - AppRepositoryProvider.php
  - Services
    - MyService.php

App\Contracts\CustomModelInterface.php

<?php namespace App\Contracts;

interface CustomModelInterface {
    public function get();
}

App\Repositories\CustomModelRepository.php

<?php namespace App\Repositories;

use App\Contracts\CustomModelInterface;
use App\Models\CustomModel;

class CustomModelRepository implements CustomModelInterface {

    private $Model;

    public function __construct(CustomModel $model) {
        $this->Model = $model;
    }

    public function get() {
        return 'result';
    }
}

App\Services\MyService.php (Keep business logic / layer between controller and repositories)

<?php namespace App\Services;

use App\Contracts\CustomModelInterface;

class MyService {

    private $Model;

    public function __construct(CustomModelInterface $customModel) {
        $this->Model= $customModel;
    }

    public function getAll() {
        return $this->Model->get();
    }
}

App\Providers\AppRepositoryProvider.php

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppRepositoryProvider extends ServiceProvider {

    public function boot() {}

    public function register() {
        $models = array(
            'CustomModel'
        );

        foreach ($models as $idx => $model) {
            $this->app->bind("App\Contracts\{$model}Interface", "App\Repositories\{$model}Repository");
        }
    }
}

My controller looks like:

<?php namespace App\Http\Controllers;

use App\Services\MyService;

class SuperController extends Controller {

    private $My;

    public function __construct(MyService $myService) {
        $this->My = $myService;
    }

    public function getDetails() {
        return $this->My->getAll();
    }
}

composer.json

"autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/",
            "App\\Models\\": "app/Models/",
            "App\\Contracts\\": "app/Contracts/",
            "App\\Repositories\\": "app/Repositories/"
        }
    },

10条回答
冷血范
2楼-- · 2019-02-02 20:24

The last thing you do is to use the interface you bound to the repository.

Set it up and try running your laravel app to make sure you get no errors.

In my case I had a mismatch between my repository and interface.

interface UserRepositoryInterface{
  public function get($userId); 
}

class UserRepository implements UserRepositoryInterface{
  public function get(int $userId);
}

As you can see the interface get method does not include a type hint but the UserRepository class' get method has a type hint.

You won't get this error if you immediately start to use your Interface Binding.

查看更多
放荡不羁爱自由
3楼-- · 2019-02-02 20:26

Don't worry guys. I have a solution to your problem.

I have an example for you.

Step1: php artisan make:repository Repository/Post //By adding this command you can create a repository and eloquent files

Step2: After adding that file you have to add/use this repository in the controller in which you want to use.

for eg: use App\Repositories\Contracts\PostRepository;

Step3: After adding that repo in your controller if you will run the app you will get an error like " Interface is not instantiable". It comes because you have created a repo and used in a controller, but laravel don't know where this repository is register and bind with which eloquent. So that it throws an error.

Step4: To solve this error you have to bind your repo with your eloquent in AppServiceProvider. E.g:

AppServiceProvider.php file

<?php
namespace App\Providers;

// **Make sure that your repo file path and eloquent path must be correct.**

use App\Repositories\Contracts\PostRepository;         // **Use your repository here**

use App\Repositories\Eloquent\EloquentPostRepository;  **// Use your eloquent here**

use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider {
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register() {

**// And bind your repository and eloquent here. **

        $this->app->bind(PostRepository::class, EloquentPostRepository::class);
    }
}

Step5: After binding repo and eloquent you can use all method of repo in your controller. Enjoy.....

Please let me know if you have any query.

查看更多
Deceive 欺骗
4楼-- · 2019-02-02 20:28

I got past this error running:

php artisan config:clear
php artisan clear-compiled
php artisan optimize
php artisan config:cache

Related to:

Target is not instantiable. Laravel 5 - App binding service provider

查看更多
可以哭但决不认输i
5楼-- · 2019-02-02 20:31

Thank you everyone, but problem was in my AppRepositoryProvider. As it's binding exception, then obviously the problem was with binding :)

Correct file is:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class AppRepositoryProvider extends ServiceProvider {

    public function boot() {}

    public function register() {
        $models = array(
            'CustomModel',
            'CustomModel2',
            'CustomModel3'
        );

        foreach ($models as $model) {
            $this->app->bind("App\Contracts\\{$model}Interface", "App\Repositories\\{$model}Repository");
        }
    }
}

Note, that I'm using "App\Contracts\\{$model}Interface" (not escaping "{" symbol) and it generate correct string App\Contracts\CustomModelInterface instead of App\Contracts\{$model}Interface (with unexpected escaping).

查看更多
Emotional °昔
6楼-- · 2019-02-02 20:32

Every time I create a new repository/contract pair I make sure I do the following:

  1. check the classes used in the service provider (copy/paste the namespaces)
  2. register a new binding in config/app.php
  3. php artisan optimize

Many hours of useless debugging led me to this short checklist.

查看更多
劳资没心,怎么记你
7楼-- · 2019-02-02 20:33

I think the problem here is that you don't bind App\Contracts\CustomModelInterface to anything so Laravel tries to create instance of interface.

In App\Providers\AppRepositoryProvider.php you have only:

$models = array(
            'Model'
        );

but you should have in this array CustomModel also, so it should look like this:

$models = array(
            'Model',
            'CustomModel',
        );
查看更多
登录 后发表回答