
thinkphp3.2自定义闭包事务类
自定义闭包事务类,thinkphp3.2自定义闭包事务类
<?php namespace Common\Service; /** * 事务服务类 * User: linyushan * Date: 2018/10/25 * Time: 9:10 */ class TransactionService { /** * 创建自己的实例 * @return TransactionService */ public static function createInstance() { return new self(); } /** * 返回错误码 * @var int */ private $error_code = 0; /** * @var string 错误返回描述 */ private $error_msg = ''; /** * @var array 错误返回数据 */ private $error_data = []; /** * @var array 正确返回数据 */ private $result_data = []; /** * 闭包事务 * @param string $func * @return bool * @throws CException */ public function begin($func = '') { $this->_clear(); //清理数据 if (empty($func)) { return false; } M()->startTrans(); try { $this->result_data = $func(); M()->commit(); } catch (\Exception $e) { $this->error_msg = $e->getMessage(); $this->error_code = $e->getCode(); //返回的错误码 M()->rollback(); return false; } return true; } /** * 设置错误返回数据 */ public function setErrorData($data = []) { return $this->error_data = $data; } /** * 获取错误返回数据 */ public function getErrorData() { return $this->error_data; } /** * 获取正确返回数据 */ public function getResultData() { return $this->result_data; } /** * 获取错误消息 */ public function getErrorMsg() { return $this->error_msg; } /** * 获取错误码 */ public function getErrorCode(){ return $this->error_code; } /** * 清理数据 */ private function _clear() { $this->error_data = $this->result_data = []; $this->error_msg = ''; $this->error_code = 0; } /** * 异常抛送方法 * @param $msg * @throws Exception */ public function E($msg = '') { throw new \Exception($msg); } }