zend framework2 的transaction
2014年03月17日
zend framework2 可以通过以下方式实现transaction。
*注*:在别的地方,设置了名称为valuation_objects的Session,此Session包含一个多维数组。
$adapter的$this->config是通过ServiceManager处理的,也可以通过由浅入深详细剖析Zend Framework 2 数据库连接,获取数据实现。
public function saveObjectsAction() { $sessionObjects = new Container('valuation_objects'); $objects = $sessionObjects->objects; $valuationId = $this->params()->fromRoute('id'); $sessionObjects->objects = null; $adapter = new Adapter($this->config); $connection = null; try{ //如果将下面这一行的注释去掉,数组编号为20的entity的id设置为null,将会执行数据写入操作的回滚处理, //$objects[20]['entity']['id'] = null; $connection = $adapter->getDriver()->getConnection(); $connection->beginTransaction(); foreach ($objects as $key => $object) { foreach($object['valuateUsers'] as $val) $adapter->query( "INSERT INTO valuation_objects(valuate_user_id, valuated_user_id, valuation_id) VALUES (?, ?, ?);", array($object['entity']['id'], $val['id'], $valuationId) ); } $connection->commit(); $valuationTable = $this->getServiceLocator()->get('ValuationTable'); $valuationTable->updateDecide($valuationId, 1); } catch (Exception $e) { if ($connection instanceof \Zend\Db\Adapter\Driver\ConnectionInterface) { $connection->rollback(); } } }