问题
I have developed a new Doctrine type to encrypt strings.
<?php
namespace App\Doctrine\DBAL\Types;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\StringType;
use App\Security\Encoder\OpenSslEncoder;
class EncryptedStringType extends StringType {
const MTYPE = 'encrypted_string';
private $cypherMethod;
private $iv;
private $privateKey;
public function convertToPHPValue($value, AbstractPlatform $platform)
{
$openSslEncoder = new OpenSslEncoder($this->cypherMethod, $this->iv, $this->privateKey);
return $openSslEncoder->decrypt($value);
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
$openSslEncoder = new OpenSslEncoder($this->cypherMethod, $this->iv, $this->privateKey);
return $openSslEncoder->encrypt($value);
}
public function getName()
{
return self::MTYPE;
}
/**
* @param mixed $cypherMethod
*/
public function setCypherMethod($cypherMethod)
{
$this->cypherMethod = $cypherMethod;
}
/**
* @param mixed $iv
*/
public function setIv($iv)
{
$this->iv = $iv;
}
/**
* @param mixed $privateKey
*/
public function setPrivateKey($privateKey)
{
$this->privateKey = $privateKey;
}
}
In the old Symfony3 applications, I registered the new type in the following way:
<?php
namespace AppBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\DBAL\Types\Type;
class AppBundle extends Bundle
{
public function __construct()
{
Type::addType('encrypted_string', 'AppBundle\Doctrine\DBAL\Types\EncryptedStringType');
}
public function boot()
{
$encryptedString = Type::getType('encrypted_string');
$encryptedString->setCypherMethod($this->container->getParameter('open_ssl_cypher_method'));
$encryptedString->setIv($this->container->getParameter('open_ssl_iv'));
$encryptedString->setPrivateKey($this->container->getParameter('open_ssl_private_key'));
}
}
How I can do the same in the new Symfony4 applications? I know that I can register a new type in the doctrine.yaml config file. But I need to set the cypher parameters... How I can set the object parameters in the new version?
Thank you very much.
回答1:
In the same way, Symfony 4 Kernel class has a boot() method with similar purpose, so you can move that code there for sure:
// src/Kernel.php
class Kernel extends BaseKernel
{
// ...
public function boot()
{
parent::boot();
// move here.
}
// ...
来源:https://stackoverflow.com/questions/48154380/how-to-pass-parameters-to-a-custom-doctrine-type-in-symfony4