【问题标题】:How obtain Guard without facades (without static)如何获得没有门面的Guard(没有静态)
【发布时间】:2015-02-09 13:59:57
【问题描述】:

使用静态上下文(外观),以下代码可以工作:

$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 容器中没有绑定。那么如何获取呢?

【问题讨论】:

    标签: php laravel laravel-4 non-static


    【解决方案1】:

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

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

    【讨论】:

    • 我需要在路由器中添加一些魔法来完成这项工作吗?如果我向构造函数添加一个参数,我会得到'ReflectionException' with message 'Class Illuminate\Contracts\Auth\Guard does not exist',如果我将它添加到控制器方法,我会得到Argument 1 passed to RpcController::get() must be an instance of Illuminate\Contracts\Auth\Guard, none given(我使用的是 Laravel 4)。
    • 哎呀-对不起-我在想 Laravel 5
    • 我不记得是use Illuminate\Auth\AuthManager as $auth 还是use Illuminate\Auth\Guard as Auth。两个都试试
    • use Illuminate\Auth\Guard as Auth 编译,但我得到Illuminate\Container\BindingResolutionException' with message 'Target [Illuminate\Auth\UserProviderInterface] is not instantiable.
    • AuthManager 有效。但我真正的问题是从 AuthManager 获取 Guard。 :)
    【解决方案2】:

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

    ...但是界面当然不能保证你得到的东西是像警卫一样的东西。只希望最好的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2011-05-08
      • 2013-04-27
      • 2016-01-15
      • 2022-11-28
      • 2011-10-16
      相关资源
      最近更新 更多