2013-12-20 83 views
6

我试图通过一个额外的方法扩展Laravel的Auth Guard类,所以我最后可以调用Auth::myCustomMethod()如何扩展Laravel的Auth Guard类?

继文档部分Extending The Framework我被困在如何完全做到这一点,因为Guard类本身没有自己的IoC binding,我可以重写。

下面是一些代码展示了我想要做的事:

namespace Foobar\Extensions\Auth; 

class Guard extends \Illuminate\Auth\Guard { 

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

} 

现在我应该怎么注册扩展的类Foobar\Extensions\Auth\Guard用于代替原来的Illuminate\Auth\Guard的,所以我能够调用Auth::myCustomMethod()的与例如相同的方式Auth::check()

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

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

回答

8

我会创建我自己的UserProvider服务,其中包含我想要的方法,然后扩展身份验证。

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

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

这是一个很好的tutorial you can follow to get a better understanding

有可以使用另一种方法。这将涉及扩展目前的供应商之一,如Eloquent。

class MyProvider extends Illuminate\Auth\EloquentUserProvider { 

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

然后你可以像上面那样扩展auth,但是使用你的自定义提供者。

\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`的代码。

+0

Thanks f或者你的答案大卫!我希望有一个比创建自己的UserProvider来扩展Guard类更简单的方法。我会等一段时间看看是否有其他建议。 –

+0

@HolgerWeis我已经添加了一个简单的方法来扩展Auth与当前Eloquent驱动程序的扩展名。 “Auth :: extend”代码应该按原样工作。 –

-7

只添加(也取代现有的功能)的方法是在你的项目中创建Guard.php文件的副本,并在应用程序/启动/ global.php附加:

require app_path().'/models/Guard.php'; 

中当然这是丑陋的方法,但我花了一个多小时来测试所有可能性[如何通过身份验证更改存储在会话中的内容],并且总是以错误结尾: ... HSGuard类的构造需要第一个参数为“UserProviderInterface”并获取'EloquentUserProvider'...

+0

非常不好的解决方案。它不是Laravel的工作方式。 – Jithin