将 EloquentUserProvider 与不同的哈希器 - 上下文绑定一起使用



我正在处理一个具有旧版用户数据库的项目。我必须编写自己的哈希类(实现"Illuminate\Contracts\Hashing\Hasher")才能生成和检查现有的哈希。这部分相当容易,运行良好。

我遇到的问题是让"EloquentUserProvider"使用我的哈希实现而不是默认的"BcryptHasher"。

在这种情况下,上下文绑定看起来很理想,但我找不到很多使用它的例子,所以我真的在黑暗中刺伤。

关于如何为一般哈希任务保留默认"BcryptHasher"的任何想法(例如。 Hash::make()),同时强制"EloquentUserProvider"使用我的哈希类?

这是我到目前为止所拥有的(在"config/app.php"中注册为提供者):

namespace AppProviders;
class LegacyHashServiceProvider extends IlluminateHashingHashServiceProvider
{
    public function register()
    {
        $this->app->when('IlluminateAuthEloquentUserProvider')
            ->needs('IlluminateContractsHashingHasher')
            ->give('AppClassesLegacyHash');
    }
}

我得到的错误是:

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', AppClassesLegacyHash::class);
    }
    public function provides()
    {
        return ['hash'];
    }
}

最新更新