强制编码&用Doctrine 2解码 [英] Forcing encoding & decoding with Doctrine 2

查看:134
本文介绍了强制编码&用Doctrine 2解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用旧版泥球大泥球,使用 latin1 数据库,但可以使用 utf8 字符串。每次应用程序读取或写入数据库时​​,它都会手动解码或编码并将 utf8 编码的字符串存储在 latin1 数据库。

I'm working with a legacy big ball of mud that uses a latin1 database but works with utf8 strings. Each time the application reads or writes to database, it decodes or encodes by hand and stores utf8 encoded strings in the latin1 database.

写作时,会执行以下操作:

When writing, it does something like:

$value = utf8_encode("Iñtërnâtiônàlizætiøn")
mysql_query("INSERT INTO table (key) VALUES ($value)")

因此,存储的值为IñtërnâtiÃ'nÃlizÃ|tiøn

阅读时:

$result = mysql_query("SELECT key FROM table")
$value = utf8_decode($result) // Wich results on "Iñtërnâtiônàlizætiøn" again

如何使用Doctrine 2管理相同的数据库并尊重这种奇怪的行为?

How can I manage the same database using Doctrine 2 and respecting that strange behaviour?

在我的实体中使用时,按照预期工作,但我正在寻找一个更干净和干的解决方案。

The following code will work as expected when used in my Entity, but I'm looking for a cleaner and DRY solution.

public function setKey($value)
{
    $this->key = utf8_encode($value);
}

public function getKey()
{
    return utf8_decode($this->key);
}


推荐答案

string类型,并覆盖 Doctrine\ DBAL\Types\Type 中的类。 Type :: convertToDatabaseValue Type :: convertToPHPValue 将是您要覆盖的。

You could create your own custom "string" type and override it's class in Doctrine\DBAL\Types\Type. Type::convertToDatabaseValue and Type::convertToPHPValue would be what you want to override.

<?php
use Doctrine\DBAL\Types\StringType;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class Utf8StringType extends StringType
{
    /**
     * {@inheritdoc}
     */
    public function convertToDatabaseValue($value, AbstractPlatform $p)
    {
        // convert from utf8 to latin1
        return mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
    }

    /**
     * {@inheritdoc}
     */
    public function convertToPHPValue($value, AbstractPlatform $p)
    {
        // convert from latin1 to utf8
        return mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
    }
}

然后使用新名称将类型放入Doctrine替换字符串类型:

Then put the type into Doctrine with a new name or replace the string type:

<?php
\Doctrine\DBAL\Types\Type::addType('utf8string', 'Utf8StringType');
// replace the default string type
\Doctrine\DBAL\Types\Type::overrideType('string', 'Utf8StringType');

这篇关于强制编码&amp;用Doctrine 2解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆