我试图通过一种额外的方法扩展Laravel的Auth Guard类,所以我能够Auth::myCustomMethod()
在最后调用.
在文档部分扩展框架之后,我一直坚持如何正确地执行此操作,因为Guard类本身没有自己的IoC绑定,我可以覆盖它.
这是一些代码,展示了我正在尝试做的事情:
namespace Foobar\Extensions\Auth; class Guard extends \Illuminate\Auth\Guard { public function myCustomMethod() { // ... } }
现在我应该如何注册Foobar\Extensions\Auth\Guard
要使用的扩展类而不是原始类,Illuminate\Auth\Guard
所以我能够以Auth::myCustomMethod()
与例如相同的方式调用Auth::check()
?
一种方法是替换中的Auth
别名,app/config/app.php
但我不确定这是否真的是解决这个问题的最佳方法.
顺便说一句:我正在使用Laravel 4.1.
我将创建自己的UserProvider服务,其中包含我想要的方法,然后扩展Auth.
我建议您创建自己的服务提供程序,或直接在其中一个启动文件中扩展Auth类(例如start/global.php
).
Auth::extend('nonDescriptAuth', function() { return new Guard( new NonDescriptUserProvider(), App::make('session.store') ); });
这是一个很好的教程,您可以遵循以获得更好的理解
您可以使用另一种方法.它将涉及扩展当前的提供者之一,如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`.