Laravel将哨兵用户注入模型



我希望我的代码能够解耦并为测试做好准备。

我有一个Eloquent模型。getBudgetConvertedAttribute依赖于哨兵用户属性。

public function getBudgetConvertedAttribute()
{
    return Sentry::getUser()->currency * $this->budget;
}

在测试时抛出错误,因为Sentry::getUser返回null。

我的问题是,我应该如何编码注入用户到模型从控制器或服务提供商绑定或测试?

在构造函数中注入一个$sentry对象作为依赖项,而不是使用sentry Facade。

例子
 use PathToSentry;
 class ClassName
 {
   protected $sentry
   public function __construct(Sentry $sentry)
   {
      $this->sentry = $sentry;
   }
   public function methodName() 
   {
    $this->sentry->sentryMethod();
   }
 }

为什么不直接在模型上创建一个方法,然后将Sentry用户对象作为参数呢?

public function getBudgetConverted(SentryUser $user)
{
    return $user->currency * $this->budget;
}

您需要将类型提示(SentryUser)更改为用户类的实际名称。

如果这是为了帮助测试,您可以更进一步,在接口上进行类型提示(无论如何都应该这样做),这样您就可以使用模拟用户对象来测试您的方法,而不是像Eloquent模型那样使用可能具有其他依赖关系的对象(如数据库连接)来测试方法。

最新更新