[英]Unable to inject dependency in Middleware in Laravel 5.2
我正在使用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为空,并且不会被注入。
这是我在CategoryRepo模型中的getTreeViewCategories()方法。
function getTreeViewCategories()
{
$items = array();
return $items;
}
如您所见,我在模型中什么也没做,只是为了确保注入工作正常。 我的代码有什么问题?
您未在此处分配对象属性:
function __construct(CategoryRepo $categoryParam)
{
$categoryRepo = $categoryParam;
}
更改为此:
function __construct(CategoryRepo $categoryParam)
{
$this->categoryRepo = $categoryParam
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.