我有一个类,我正试图用依赖注入来交换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''MCryptoEncrypter给定
facade解决了问题,但我想了解DI失败的原因。
use Illuminate'Support'Facades'Crypt;
Crypt::encrypt('somevalue');
感谢您的帮助。
因为您注册了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.
替换加密程序到it接口的具体实现。
facade解决了问题,但我想了解DI失败的原因。
Facade之所以有效,是因为他只解决了你注册的内容,在你的情况下是McryptEncrypter
希望它能有所帮助。
Laravel Encrypter
接口的FQCN是:
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按预期工作。