如何扩展Laravel的Auth Guard类? [英] How to extend Laravel's Auth Guard class?

查看:404
本文介绍了如何扩展Laravel的Auth Guard类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过以下方式扩展Laravel的Auth Guard 类另一种方法,因此我可以在最后调用Auth::myCustomMethod().

I'm trying to extend Laravel's Auth Guard class by one additional method, so I'm able to call Auth::myCustomMethod() at the end.

在文档部分之后扩展框架我被困在如何准确地做到这一点上,因为Guard类本身并没有拥有自己的 IoC绑定,我可以对其进行覆盖.

Following the documentation section Extending The Framework I'm stuck on how to exactly do this because the Guard class itself doesn't have an own IoC binding which I could override.

下面是一些代码,展示了我正在尝试做的事情:

Here is some code demonstrating what I'm trying to do:

namespace Foobar\Extensions\Auth;

class Guard extends \Illuminate\Auth\Guard {

    public function myCustomMethod()
    {
        // ...
    }

}

现在我应该如何注册要使用的扩展类Foobar\Extensions\Auth\Guard而不是原始的Illuminate\Auth\Guard,因此我可以像以下方法一样调用Auth::myCustomMethod(): Auth::check()?

Now how should I register the extended class Foobar\Extensions\Auth\Guard to be used instead of the original Illuminate\Auth\Guard so I'm able to call Auth::myCustomMethod() the same way as e.g. Auth::check()?

一种方法是替换app/config/app.php中的Auth别名,但是我不确定这是否真的是解决此问题的最佳方法.

One way would be to replace the Auth alias in the app/config/app.php but I'm not sure if this is really the best way to solve this.

顺便说一句:我正在使用Laravel 4.1.

BTW: I'm using Laravel 4.1.

推荐答案

我将创建自己的UserProvider服务,其中包含所需的方法,然后扩展Auth.

I would create my own UserProvider service that contain the methods I want and then extend Auth.

我建议创建您自己的服务提供商,或者直接在其中一个起始文件(例如start/global.php)中扩展Auth类.

I recommend creating your own service provider, or straight up extending the Auth class in one of the start files (eg. start/global.php).

Auth::extend('nonDescriptAuth', function()
{
    return new Guard(
        new NonDescriptUserProvider(),
        App::make('session.store')
    );
});

这是一个很好的教程,您可以按照该教程获得更好的理解

您可以使用另一种方法.这将涉及扩展Eloquent之类的当前提供商之一.

There is another method you could use. It would involve extending one of the current providers such as Eloquent.

class MyProvider extends Illuminate\Auth\EloquentUserProvider {

    public function myCustomMethod()
    {
        // Does something 'Authy'
    }
}

然后,您可以像上面那样使用自定义提供程序扩展auth.

Then you could just extend auth as above but with your custom provider.

\Auth::extend('nonDescriptAuth', function()
{
    return new \Illuminate\Auth\Guard(
        new MyProvider(
            new \Illuminate\Hashing\BcryptHasher,
            \Config::get('auth.model')
        ),
        \App::make('session.store')
    );
});

一旦实现了代码,就可以将auth.php配置文件中的驱动程序更改为使用'nonDescriptAuth`.

Once you've implemented the code you would change the driver in the auth.php config file to use 'nonDescriptAuth`.

这篇关于如何扩展Laravel的Auth Guard类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆