如何获得没有门面的Guard(没有静态)

How obtain Guard without facades (without static)

使用静态上下文(外观)以下代码有效:

$result = Auth::attempt(Input::only('email', 'password'));

假设我想将静态上下文减少到最低限度(据说 Laravel 可以实现)。

我正在做一个小的妥协并获得对应用程序的引用:

/* @var $app Illuminate\Foundation\Application */
$app = App::make("app");

...然后获取授权管理器:

/* @var $auth \Illuminate\Auth\AuthManager */
$auth = $app->get("auth");

现在的问题是:AuthManager 没有 attempt 方法。 Guard 确实如此。唯一的问题:Guard 在 IoC 容器中没有绑定。那么如何获取呢?

你可以只使用依赖注入并得到它

use Illuminate\Auth\Guard as Auth;

public $auth;

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

public function doSomething()
{
    $this->auth->attempt(Input::only('email', 'password'));
}

和p.s。 Guard 不是静态引用 - 它是一个外观,在被引用时创建一个实例。所以你仍然可以测试等。但那是另一个时间的讨论:)

AuthManagerManager 继承了 driver() 方法,这将提供一个 驱动程序实例 (显然是 Guard)。

管理器还使用魔术将对不存在的函数的任何调用转发给驱动程序:

public function __call($method, $parameters)
{
    return call_user_func_array(array($this->driver(), $method), $parameters);
}

所以,回答我自己的问题:

/* @var $manager \Illuminate\Auth\AuthManager */
$manager = $app->get("auth");

/* @var $guard \Illuminate\Auth\Guard */
$guard = $manager->driver();

...但是界面当然不能保证你得到的是守卫。只希望最好的。