Zend DB Row的自定义属性

时间:2014-08-27 17:45:44

标签: php database zend-framework

考虑以下代码:

$select = $table->select()->setIntegrityCheck(false);
$row = $table->fetchRow($select);

// this throws Specified column "custom_data" is not in the row
$row->custom_data = 123;

echo $row->custom_data;

如何将一些自定义数据添加到zend db row?

1 个答案:

答案 0 :(得分:2)

如果要将临时数据添加到行对象,使其实际上没有使用行保存,请不要使用属性,请在行类中使用setter方法:

protected $customData = null;

public function getCustomData()
{
    return $this->customData;
}

public function setCustomData($data)
{
    $this->customData = $data;
    return $this;
}

然后从你的代码中调用它:

$row->setCustomData($data);

或者,如果要对许多类执行此操作,可以覆盖Zend_Db_Table_Row_Abstract的__set()方法,这样它不会抛出异常,而是将值存储在单独的区域中:

protected $extraFields = [];

function __set($columnName, $value)
{
    $columnName = $this->_transformColumn($columnName);
    if (array_key_exists($columnName, $this->_data)) {
        $this->_data[$columnName] = $value;
        $this->_modifiedFields[$columnName] = true;
    } else {
        $this->extraFields[$columnName] = $value;
    }
}

public function __get($columnName)
{
    $columnName = $this->_transformColumn($columnName);
    if (array_key_exists($columnName, $this->_data)) {
        return $this->_data[$columnName];
    } else {
        return $this->extraFields[$columnName];
    }
}