【问题标题】:Use Symfony's serializer through dependency injection inside a custom Doctrine Type in Symfony [duplicate]通过在 Symfony 中的自定义 Doctrine 类型中的依赖注入使用 Symfony 的序列化程序 [重复]
【发布时间】:2020-09-28 15:11:32
【问题描述】:

我在 symfony 中制作了一个自定义的 Doctrine Type,它扩展了 Doctrine\DBAL\Types\Type

我需要在那里注入 symfony 的序列化器,以使用 symfony 的序列化器解码一些 JSON,以便它可以对特定的类进行水合。

但是,我无法覆盖构造函数,因为它是最终的,也无法注入 SerializerInterface

我尝试使用 setter 并注入 SerializerInterface,但它不起作用。

class MyCustomDoctrineType extends Type
{

    private const NAME = 'my_custom_type';

    /**
     * {@inheritdoc}
     */
    public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return $platform->getJsonTypeDeclarationSQL($fieldDeclaration);
    }

    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if ($value === null) {
            return null;
        }

        return $value;
    }


    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        if ($value === null || $value === '') {
            return null;
        }

        if (is_resource($value)) {
            $value = stream_get_contents($value);
        }

        $this->serializer->deserialize($value, MyClass::class, 'json'); // this is what I want to accomplish

        return $value;
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }


    public function getName()
    {
        return self::NAME;
    }
}

有没有办法在那里进行依赖注入?

【问题讨论】:

  • 谢谢@emix,这有帮助。我在 symfony 4 的 src/Kernel 中添加了一个 boot() 函数,它似乎正在工作 public function boot() { parent::boot(); \Doctrine\DBAL\Types\Type::getType(JsonRaw::NAME)->setSerializer($this->container->get('serializer')); }

标签: symfony doctrine


【解决方案1】:

正如@emix 所指出的,在 Symfony 4 中,您可以覆盖 Kernel.php 中的 boot() 函数并从那里手动注入依赖项

public function boot()
{
    parent::boot();
    \Doctrine\DBAL\Types\Type::getType('my_type_name')->setSerializer($this->container->get('serializer'));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-15
    • 1970-01-01
    • 2012-07-17
    相关资源
    最近更新 更多