@drew010 像往常一样是正确的,把这些函数放在你的映射器中。老实说,这些可能都可以放在抽象或基本映射器中,因此您的所有映射器都可以使用该功能。
您可以轻松地在映射器中创建一个函数 recordExists() 并将表和列作为参数传递:
//you can either pass in the table name or have it be a property
public function recordExists($table = null, $column) {
//The table syntax may change depending on the scope
$table = $this->_tableName;
$exists = new Zend_Validate_Db_RecordExists(array(
'table' => $table,
'field' => $column
)):
return $exists;
}
对于 findBy() 方法,我喜欢将 3 个变量传递给该方法,然后使用 fetchAll() 返回一个对象数组。这样,如果列返回一行或五十行,我以相同的方式处理输出。
/**
* findByColumn() returns an array of rows selected
* by column name and column value.
* Optional orderBy value, pass $order as string ie 'id ASC'.
*
* @param string $column
* @param string $value
* @param string $order
* @return array returns an array of objects
*/
public function findByColumn($column, $value, $order = NULL) {
$select = $this->_getGateway()->select();
$select->where("$column = ?", $value);
if (!is_null($order)) {
$select->order($order);
}
$result = $this->_getGateway()->fetchAll($select);
$entities = array();
foreach ($result as $row) {
//create objects
$entity = $this->createEntity($row);
$entities[] = $entity;
}
return $entities;
}
至于你的最后一个问题,你可以通过获取行然后只保存开关来激活 aa 记录,我认为你设置了某种类型的标志或布尔值来激活记录。这可能需要进入具体的 UserMapper,因为我发现使用我用来保存记录的方法,基本的 save() 方法并不总是有效。
//you'll set the activate switch when the user object is instantiated
public function activate(Application_Model_User $user) {
if (!is_null($user->id)) {
$select = $this->_getGateway()->select();
$select->where('id = ?', $user->id);
$row = $this->_getGateway()->fetchRow($select);
$row->activate = $user->activate;
//This is the cool thing about save(), you can change as many or few columns as you need.
$row->save()
return $row;
} else {
//handle error, as we only want to be able to change an existing user.
}
}
这可能比您需要的更多,但我希望它有所帮助。