无法在Laravel 5.2中的中间件中注入依赖项

问题描述 投票:1回答:1

我正在使用Laravel 5.2开发Web应用程序。我知道Laravel支持依赖注入。我是在中间件中做的。但是不会注入依赖项,并且注入的类的实例始终为null。这就是我所做的。

这是我的中间件

class StoreMiddleware
{
    private $categoryRepo;

    function __construct(CategoryRepo $categoryParam)
    {
        $categoryRepo = $categoryParam;
    }

    public function handle($request, Closure $next)
    {
        $categories = $this->categoryRepo->getTreeViewCategories();
        view()->share(['categories'=>$categories]);
        return $next($request);
    }
}

我在内核中这样声明了

protected $routeMiddleware = [
        .
        .
        .
        'store' =>\App\Http\Middleware\StoreMiddleware::class
    ];

我这样配置路由

Route::group(['middleware'=>'store'],function(){
    Route::get('home','HomeController@index');
    Route::get('/','HomeController@index');
});

当我访问主页时,它给了我这个错误

FatalThrowableError in StoreMiddleware.php line 20:
Call to a member function getTreeViewCategories() on null

正如您所看到的,它表示categoryRepo为null并且不会被注入。

这是CategoryRepo模型中的getTreeViewCategories()方法。

function getTreeViewCategories()
    {
        $items = array();
        return $items;
    }

正如你所看到的,我在模型中没有做任何事情只是为了确保注射是否有效。我的代码出了什么问题?

php dependency-injection laravel-5.2 laravel-middleware
1个回答
2
投票

您没有在此处分配对象属性:

function __construct(CategoryRepo $categoryParam)
{
    $categoryRepo = $categoryParam;
}

把它改成这个:

function __construct(CategoryRepo $categoryParam)
{
    $this->categoryRepo = $categoryParam
}
© www.soinside.com 2019 - 2024. All rights reserved.