I\'m using Symfony 2 with Doctrine 2.
I need to encrypt a field in my entity using an encryption service, and I\'m wondering where should I put this logic.
I\'m
To expand on richsage and targnation's great answers, one way to inject a dependency (e.g., cypto service) into a custom Doctrine mapping type, could be to use a static property and setter:
// MyBundle/Util/Crypto/Types/EncryptedString.php
class EncryptedString extends StringType
{
/** @var \MyBundle\Util\Crypto */
protected static $crypto;
public static function setCrypto(Crypto $crypto)
{
static::$crypto = $crypto;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
$value = parent::convertToDatabaseValue($value, $platform);
return static::$crypto->encrypt($value);
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
$value = parent::convertToPHPValue($value, $platform);
return static::$crypto->decrypt($value);
}
public function getName()
{
return 'encrypted_string';
}
}
Configuration would look like this:
// MyBundle/MyBundle.php
class MyBundle extends Bundle
{
public function boot()
{
/** @var \MyBundle\Util\Crypto $crypto */
$crypto = $this->container->get('mybundle.util.crypto');
EncryptedString::setCrypto($crypto);
}
}
# app/Resources/config.yml
doctrine:
dbal:
types:
encrypted_string: MyBundle\Util\Crypto\Types\EncryptedString
# MyBundle/Resources/config/services.yml
services:
mybundle.util.crypto:
class: MyBundle\Util\Crypto
arguments: [ %key% ]