我该如何在 Laravel 中进行依赖注入 Auth?
可以这样:
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
如果我这样做,那么这个就不能工作:
$user_type = Auth::user()->user_type;
我该如何在 Laravel 中进行依赖注入 Auth?
可以这样:
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
$user_type = Auth::user()->user_type;
你应该对Illuminate\Auth\AuthManager
进行类型提示:
public function __construct(Illuminate\Auth\AuthManager $auth)
{
$this->auth = $auth;
}
如果您想注入Auth,实际上需要注入这个类:
use Illuminate\Contracts\Auth\Guard;
这将解决你在其中定义的所有内容:
config/auth.php
Guard Driver,即Guard Class - 它需要实现Guard或StatefulGuard接口。
提供程序,即UserProvider Class - 它需要实现UserProvider接口。
Laravel / Lumen中的标准Auth Guard驱动程序包括:
Laravel / Lumen中的标准Auth UserProviders包括:
有关扩展Auth的更多信息,请参阅官方Laravel文档。请参见下面的链接:
https://laravel.com/docs/5.0/extending#authentication
这是我在控制器中的代码,它运行得非常好:
public function createToken(Request $request, Guard $guard)
{
// return 'in progress...';
}
在ServiceProvider的boot()方法中扩展Auth类是最佳实践。
希望这能帮到你!
祝好!
$this->auth->user()->user_type
,一定会抛出Trying to get property of non-object
异常。 - BogdanAuthManager
。请查看此答案。 - Bogdan