2013-12-20 75 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