首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >拉拉维尔依赖注入8月::

拉拉维尔依赖注入8月::
EN

Stack Overflow用户
提问于 2017-03-01 15:44:23
回答 2查看 683关注 0票数 4

我有一个带有CalendarService的laravel项目,我将该服务注入我的控制器。在建设者中,我会做这样的事情:

CalendarService.php

代码语言:javascript
复制
/** @var Collection|Timelog[] */
private $timelogs;

public function __construct()
{
    $this->currentRoute = URL::to( '/' ) . "/home";
    $this->timelogs     = Auth::user()->timelogs()->get();
    $this->currentDay   = 0;
}

HomeController.php

代码语言:javascript
复制
/** @var CalendarService */
protected $calenderService;

public function __construct
(
    CalendarService $calendarService
)
{
    $this->calenderService = $calendarService;
}

我得到了这个错误

对null调用成员函数timelogs()

关于这一行代码:

代码语言:javascript
复制
Auth::user()->timelogs()->get();

我在服务中使用了use Illuminate\Support\Facades\Auth;

这里发生什么事情?

EN

回答 2

Stack Overflow用户

发布于 2017-03-01 15:52:23

问题在于(正如https://laracasts.com/discuss/channels/laravel/cant-call-authuser-on-controllers-constructor中所指出的),Auth中间件在控制器构建阶段没有初始化。

但是,您可以这样做:

代码语言:javascript
复制
protected $calenderService;

public function __construct()
{ 
    $this->middleware(function ($request,$next) {        
         $this->calenderService = resolve(CalendarService::class);
         return $next($request);
     });
}

替代方案

代码语言:javascript
复制
public function controllerMethod(CalendarService $calendarService) { 
    //Use calendar service normally
}

注意:这假设您能够通过服务容器解析CalendarService

票数 1
EN

Stack Overflow用户

发布于 2017-03-01 15:49:42

在最新版本的Laravel中,不能在构造函数中使用auth()Auth::,因此需要在方法中直接使用此逻辑。

代码语言:javascript
复制
public function someMethod()
{
    $timelogs = Auth::user()->timelogs()->get();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42536091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档