簡體   English   中英

將EloquentUserProvider與其他Hasher一起使用-上下文綁定

[英]Use EloquentUserProvider with different Hasher - Contextual Binding

我正在開發一個具有舊版用戶數據庫的項目。 我必須編寫自己的Hasher類(實現“ Illuminate \\ Contracts \\ Hashing \\ Hasher”),以便生成和檢查現有的哈希。 這部分相當簡單,並且運行良好。

我遇到的麻煩是讓“ EloquentUserProvider”使用我的Hasher實現,而不是默認的“ BcryptHasher”。

在這種情況下,上下文綁定看起來很理想,但我找不到使用它的許多示例,因此我真的是在暗中摸索。

關於如何在強制“ EloquentUserProvider”使用我的Hasher類的同時如何保留默認的“ BcryptHasher”以執行常規哈希操作(例如Hash::make() )的任何想法?

這是我到目前為止(在“ config / app.php”中注冊為提供程序):

namespace App\Providers;

class LegacyHashServiceProvider extends \Illuminate\Hashing\HashServiceProvider
{
    public function register()
    {
        $this->app->when('Illuminate\Auth\EloquentUserProvider')
            ->needs('Illuminate\Contracts\Hashing\Hasher')
            ->give('App\Classes\LegacyHash');
    }
}

我得到的錯誤是:

ReflectionException in Container.php line 741:
Class hash does not exist

1.  in Container.php line 741
2.  at ReflectionClass->__construct('hash') in Container.php line 741
3.  at Container->build('hash', array()) in Container.php line 631
4.  at Container->make('hash', array()) in Application.php line 674
5.  at Application->make('hash') in Container.php line 1163
6.  at Container->offsetGet('hash') in AuthManager.php line 105
7.  at AuthManager->createEloquentProvider() in AuthManager.php line 91
8.  at AuthManager->createEloquentDriver() in Manager.php line 87
9.  at Manager->createDriver('eloquent') in AuthManager.php line 18
10. at AuthManager->createDriver('eloquent') in Manager.php line 63
...

看起來很簡單,但是我很困惑。 有任何想法嗎?

作為我的問題的跟進。

經過多次嘗試,我得出結論,Laravel從服務容器中預先構建了一個“哈希”對象,並將其注入到“ EloquentUserProvider”中。 它沒有使用類型提示來注入依賴關系,因此上下文綁定可能無法正常工作。

最后,我基本上將Laravel的默認哈希提供程序替換為我自己的。 我調整了我的“ LegacyHashServiceProvider”並將其綁定到服務容器中的“ hash”鍵。 最后,我在config / app.php文件中注釋了Laravel的默認哈希提供程序,並為“ LegacyHashServiceProvider”添加了一個條目。

我覺得上下文綁定如果可以的話,會更加優雅。

這是我的“ LegacyHashServiceProvider”中的代碼

class LegacyHashServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function register()
    {
        $this->app->singleton('hash', \App\Classes\LegacyHash::class);
    }

    public function provides()
    {
        return ['hash'];
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM