如何获得没有正面(没有静电)的防护


How obtain Guard without facades (without static)

使用静态上下文(facade),以下代码有效:

$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不是一个静态引用-它是一个在被引用时创建实例的facade。所以你仍然可以测试等等。但这是另一次的讨论:)

AuthManagerManager继承了driver()方法,该方法将为驱动程序实例(显然是Guard)。

此外,Manager使用魔术将对不存在函数的任何调用转发给驱动程序:

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();

但当然,这个界面并不能保证你得到的是像Guard一样的东西。只是抱着最好的希望。