【问题标题】:Laravel 5.1 wrong instance of Illuminate\Encryption\EncrypterLaravel 5.1 错误的 Illuminate\Encryption\Encrypter 实例
【发布时间】:2016-03-28 18:53:20
【问题描述】:

我有一个类,我试图用依赖注入替换 Crypt::encrypt 的外观用法:

       <?php namespace App\Libraries;

        use Illuminate\Encryption\Encrypter;

        class MyClass
        {

            public function __construct(Encrypter $encrypter)
            {
                $this->encrypter= $encrypter;
            }

            public function myMethod()
            {
                $this->encrypter->crypt('somevalue');
            }

         }

错误的实例正在被实例化:

传递给 App\Libraries\MyClass::__construct() 的参数 1 必须是 Illuminate\Encryption\Encrypter 的实例, 给定的 Illuminate\Encryption\McryptEncrypter

外观解决没有问题,但我想了解 DI 失败的原因。

use Illuminate\Support\Facades\Crypt;
Crypt::encrypt('somevalue');

任何帮助表示赞赏。

【问题讨论】:

    标签: php laravel dependency-injection namespaces laravel-5.1


    【解决方案1】:

    这是因为您注册了McryptEncrypter 而不是Encrypter。 如果您有不受支持的密码或密钥,则可能是这样。 更多信息请查看Illuminate\Encryption\EncryptionServiceProvider

        use Illuminate\Contracts\Encryption\Encrypter;
    
        class MyClass
        {
    
            public function __construct(Encrypter $encrypter)
            {
                $this->encrypter= $encrypter;
            }
    
            public function myMethod()
            {
                $this->encrypter->crypt('somevalue');
            }
    
         }
    

    另外,遵循SOLID原则Depend upon Abstractions. Do not depend upon concretions.将Encrypter具体实现替换为它的接口。

    外观解决没有问题,但我想了解 DI 失败的原因。

    Facade 之所以有效,是因为他只是解决了您注册的内容,在您的情况下是 McryptEncrypter

    希望它会有所帮助。

    【讨论】:

    • 正确的函数是encrypt
    • 我认为您的密码需要是“AES-128-CBC”或“AES-256-CBC”
    • 加密器没有crypt方法,但是有encrypt
    • 就像已经提到的那样,没有称为 crypt 的方法,您可以在这里看到:interface Encrypter { /** * Encrypt the given value. * * @param string $value * @return string */ public function encrypt($value); /** * Decrypt the given value. * * @param string $payload * @return string */ public function decrypt($payload); } 只有 encryptdecrypt,这个答案是正确的方法,通过使用合约
    【解决方案2】:

    Laravel 的 FQCN Encrypterinterface(我强调)是:

    • Illuminate\Contracts\Encryption\Encrypter

    你定义的方法:

            public function __construct(Encrypter $encrypter)
            {
                $this->encrypter= $encrypter;
            }
    

    不使用该接口。除非您没有使用正确的界面,否则 PHP 会正确且完全正确地向您显示错误消息并幸运地阻止您的程序运行:

    传递给 App\Libraries\MyClass::__construct() 的参数 1 必须是 Illuminate\Encryption\Encrypter 的实例,给定的 Illuminate\Encryption\McryptEncrypter 实例

    你违约了!

    为参数使用正确的接口,以便 DI 按预期工作。

    【讨论】:

      猜你喜欢
      • 2019-06-11
      • 2016-08-21
      • 1970-01-01
      • 2021-04-29
      • 2017-09-23
      • 1970-01-01
      • 2016-03-21
      • 2015-10-04
      • 2016-05-28
      相关资源
      最近更新 更多