我在 zf2 中使用表网关。这是具有以下工作功能的简单模型表。我可以插入或更新记录,但我需要知道如何定义像 beforeInsert 或 beforeUpdate 这样的函数,就像我们在教义(beforePersist)中所做的那样。
namespace Application\Model\AnyModel;
use Zend\Db\TableGateway\TableGateway;
class AnyModelTable {
protected $tableGateway;
public function __construct(TableGateway $tableGateway) {
$this->tableGateway = $tableGateway;
}
public function fetchAll() {
$resultSet = $this->tableGateway->select();
return $resultSet;
}
public function getRecord($id) {
$id = (int) $id;
$rowSet = $this->tableGateway->select(array('id' => $id));
$row = $rowSet->current();
if (!$row) {
throw new \Exception("Could not found record with $id");
}
return $row;
}
public function saveRecord(AnyModel $record) {
$data = array(
'name' => $record->name,
'description' => $record->description,
'status' => $record->status,
'created_by' => $record->created_by,
'created_on' => $record->created_on,
);
$id = (int) $record->id;
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getUser($id)) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception("Could not update user with id $id");
}
}
}
public function deleteRecord($id) {
$this->tableGateway->delete(array('id' => $id));
}
public function getArrayCopy() {
return get_object_vars($this);
}