【问题标题】:Yii - remove smart quotes for all active recordsYii - 删除所有活动记录的智能报价
【发布时间】:2013-04-12 17:50:32
【问题描述】:
我有一个允许用户导入/输入信息的应用程序,这些信息使用 Yii 活动记录保存到 MySQL 数据库中,并且我有一些用户复制/粘贴具有 Microsoft 智能引号的文本。当在网站的 iPhone 实现上解析数据时,这是一个问题,所以我需要一种方法来摆脱所有智能引号。
我找到了一个 php 函数,它可以从一段文本中删除这些字符,但我想知道 Yii 中是否有一种方法可以在每次将文本保存到数据库时调用该函数。
【问题讨论】:
标签:
php
activerecord
yii
smart-quotes
【解决方案1】:
您可以通过以下方式扩展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 以在验证之前删除引号。
【解决方案2】:
我建议为可能出现的字段创建 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;
}