存储库未实例化

时间:2015-04-07 01:11:21

标签: php laravel laravel-5 repository

我试图找出我收到此错误的原因。我跟着走了。然而唯一的区别是,在录制时,它是使用Laravel 4.25完成的,现在我正在使用Laravel 5.0。

Repositories and Inheritance

  

Container.php第785行中的BindingResolutionException:

     

目标[App \ Repositories \ User \ UserRepository]不可实例化。

<?php 
    namespace App\Http\Controllers;

    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    use App\Repositories\User\UserRepository;

    use Illuminate\Http\Request;

    class UsersController extends Controller {

        private $userRepository;

        public function __construct(UserRepository $userRepository) {
            $this->userRepository = $userRepository;
        }

        /**
         * Display a listing of the resource.
         *
         * @return Response
         */
        public function index() {
            $users = $this->userRepository->getAll();

            return $users;
        }
    }

<?php

    namespace App\Repositories\User;

    use App\Repositories\EloquentRepository;

    class EloquentUserRepository extends EloquentRepository implements UserRepository 
    {
        private $model;

        function __construct(User $model) {
            $this->model = $model;
        }
    }

<?php

    namespace App\Repositories\User;

    interface UserRepository {
        public function getAll();    
    }

<?php

    namespace App\Repositories;

    abstract class EloquentRepository {

        public function getAll() {
            return $this->model->all();
        }

        public function getById() {
            return $this->model->findOrFail($id);
        }
    }  

1 个答案:

答案 0 :(得分:2)

您是提示界面的类型,而不是类本身。发生此错误是因为Laravel无法绑定接口,因为绑定必须是可实例化的。除非Laravel知道要替换抽象类/接口的具体(可实例化)类,否则抽象类或接口无效。

您需要将EloquentUserRepository绑定到界面:

App::bind('UserRepository', 'EloquentUserRepository');