Search code examples
phplaravellaravel-4non-static

How obtain Guard without facades (without static)


Using static context (facades) the following code works:

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

Let's say I want to reduce static context to the minimum (which is said to be possible with Laravel).

I'm making a small compromise and get a reference to the application:

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

... then get the auth manager:

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

Now the problem: AuthManager has no attempt method. Guard does. The only problem: Guard has no binding in the IoC ontainer. So how to obtain it?


Solution

  • AuthManager inherits the driver() method from Manager which will give the a driver instance (which apparently is the Guard).

    Also Manager uses magic to forward any calls to non-existent functions to the driver:

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

    So, to answer my own question:

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

    ... but of course the interface won't guarantee that what you get is anything like the Guard. Just hope for the best.