1、定义事务处理接口
<?php namespace frontendusinessSaveRecordByransactions; /** * Interface ISaveForTransaction 事物提交接口 * @package frontendusinessRewardTransactions */ interface ISaveForTransaction { function SaveRecordForTransaction(&$error,&$outInfo); }
2、新建统一事务处理的方法类
<?php namespace frontendusiness; use frontendusinessSaveRecordByransactionsISaveForTransaction; use yiiaseException; use yiidbTransaction; use yiilogLogger; class SaveByTransUtil { /** * 事物保存支持 * @param $objList 需要保存的对象数组, * @param $error * @return bool * @throws yiidbException */ public static function RewardSaveByTransaction($objList,&$error,&$outInfo = null) { $error =''; if(!isset($objList) || !is_array($objList)) { $error = '非法对象,不是数组'; return false; } foreach($objList as $obj) { if(!($obj instanceof ISaveForTransaction)) { $error = '对象数组中存在非ISaveForTransaction对象'; return false; } } $outInfo = []; $trans = Yii::$app->db->beginTransaction(Transaction::REPEATABLE_READ); try { foreach($objList as $obj) { if(!$obj->SaveRecordForTransaction($error,$outInfo)) { if(is_array($error)) { Yii::getLogger()->log(var_export($error,true).' type:'.var_export($obj,true),Logger::LEVEL_ERROR); } else { Yii::getLogger()->log($error.' type:'.var_export($obj,true),Logger::LEVEL_ERROR); } $trans->rollBack(); return false; } } $trans->commit(); } catch(Exception $e) { $error = $e->getMessage(); $trans->rollBack(); return false; } return true; } }
3、要进行事务处理的方法类必须继承事务处理接口ISaveForTransaction 并重写里面的SaveRecordForTransaction方法
<?php namespace frontendusinessSaveRecordByransactionsSaveByTransaction; use frontendusinessSaveRecordByransactionsISaveForTransaction; use yiiaseException; /** * 修改增加实际豆数 * Class ModifyBalanceByTicketToCash * @package frontendusinessUserAccountBalanceActions */ class ModifyBalanceByAddRealBean implements ISaveForTransaction { private $balance = null; private $extend_params=[]; /** * @param $record * @param array $extend_params * @throws Exception */ public function __construct($record,$extend_params=[]) { $this->balance = $record; $this->extend_params = $extend_params; } public function SaveRecordForTransaction(&$error,&$outInfo) { //逻辑处理 return true; } }
4、调用事务处理
实例化不同业务处理类到数组$transActions,最后统一调用事务处理方法RewardSaveByTransaction
<?php $transActions = []; $transActions[] = new ModifyBalanceByAddRealBean($userBalance,$param); $transActions[] = new ModifyGift($params); if(!SaveByTransUtil::RewardSaveByTransaction($transActions,$error)) { return false; }