【问题标题】:Laravel: Dependency Inject AuthLaravel:依赖注入身份验证
【发布时间】:2015-01-01 19:07:25
【问题描述】:

如何在 Laravel 中依赖注入 Auth?

像这样:

 public function __construct(Auth $auth)
    {
      $this->auth = $auth;

    }

如果我这样做,那么这不起作用:

$user_type = Auth::user()->user_type;

【问题讨论】:

    标签: authentication laravel laravel-4 dependency-injection


    【解决方案1】:

    你应该输入提示Illuminate\Auth\AuthManager:

    public function __construct(Illuminate\Auth\AuthManager $auth)
    {
      $this->auth = $auth;
    }
    

    【讨论】:

    • 这不起作用。当我运行测试时... $user_type = $this->auth->user()->user_type; ...失败
    • 您有用户会话吗?因为尝试在没有用户会话的情况下获取$this->auth->user()->user_type,肯定会抛出Trying to get property of non-object 异常。
    • 嗨,抱歉!我正在尝试对控制器进行单元测试,并且上面的代码导致错误。最初我只是为 Auth 使用了外观模式,但这导致了同样的问题。
    • 在这种情况下,您应该模拟 AuthManager 进行测试。看看这个answer
    • 啊哈,这就是我一直在寻找的。​​span>
    【解决方案2】:

    如果要注入Auth,其实需要注入这个类:

    use Illuminate\Contracts\Auth\Guard;
    

    这将解决您在内部定义的所有内容:

    config/auth.php
    

    如果您想扩展 Auth,您可以这样做,但仅限于:

    1. Guard Driver 是 Guard 类 - 它需要实现 Guard 或 StatefulGuard 接口。

    2. Provider 是 UserProvider 类 - 它需要实现 UserProvider 接口。

    Laravel / Lumen 中的标准 Auth Guard 驱动程序是:

    1. SessionGuard
    2. TokenGuard

    标准的 Auth UserProviders 在 Laravel / Lumen 中是:

    1. EloquentUserProvider
    2. 数据库用户提供者

    更多关于在 Laravel 官方文档中扩展 Auth 的信息。见以下链接:

    https://laravel.com/docs/5.0/extending#authentication

    这是我在我的控制器中的代码,它的工作就像一个魅力:

        public function createToken(Request $request, Guard $guard)
        {
    //        return 'in progress...';
        }
    

    扩展 Auth 类的最佳实践是在 ServiceProvider boot() 方法中。

    希望这会有所帮助!

    干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 2012-10-09
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多