Yii - 删除所有活动记录的智能引号

时间:2013-04-12 17:50:32

标签: php activerecord yii smart-quotes

我有一个应用程序,允许用户导入/输入信息,使用Yii活动记录保存到MySQL数据库,我有一些用户复制/粘贴具有Microsoft智能引号的文本。当在网站的iPhone实现上解析数据时,这是一个问题,因此我需要一种方法来摆脱所有智能引号。

我找到了一个PHP函数,它将从一段文本中删除这些字符,但我想知道Yii中是否有一种方法可以在每次将文本保存到数据库时调用该函数。

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式扩展CActiveRecord覆盖beforeSave方法:

class ActiveRecord extends CActiveRecord
{
    protected function removeMagicQuotes($value)
    {
        return your_function_remove_magic_quotes($value);
    }

    protected function beforeSave()
    {
        $attributes = array_keys($this->getAttributes());
        foreach ($attributes as $attribute)
            $this->$attribute = $this->removeMagicQuotes($this->$attribute);  
        return parent::beforeSave();
    }
}

这个将删除活动记录中声明的所有属性的魔术引号。作为替代方案,您可以覆盖beforeValidate方法而不是beforeSave,以便在验证之前删除引号。

答案 1 :(得分:0)

我建议为可能出现的字段创建getter / setter并在那里过滤它。

如果是字段comment,则会出现类似情况:

// Make field $comment private so get/set will work
private $comment = '';
public function getComment()
{
    return clear_function($this->comment);
}

public function setComment($value)
{
    // Could clear here too if you want, so it will be stored clean in db
    $this->comment = $value;
}