首页 > 代码库 > thinkphp继承高级model后的乐观锁运用(测试中)

thinkphp继承高级model后的乐观锁运用(测试中)

 1 <?php 2 class IndexAction extends Action { 3     private $d_user; 4     private $user; 5     private $arr; 6      7     public function __construct(){ 8         parent::__construct(); 9         $this->d_user = D(‘User‘);10         $this->user = M(‘user‘);11         12         //打款的配置信息13         $this->arr = array(14             ‘userA‘ => 1,15             ‘userB‘ => 2,16             ‘money‘ => 30017         );18     }19     20     /**21      * 打款逻辑(事务操作)22      */23     public function index(){24         $this->user->startTrans();25         $this->moneyFill($this->user, $this->arr[‘userA‘], $this->arr[‘money‘]);26         27         $data = array(‘id‘ => $this->arr[‘userA‘], ‘money‘ => array(‘exp‘,‘money - ‘ . $this->arr[‘money‘]));28         $data2 = array(‘id‘ => $this->arr[‘userB‘], ‘money‘ => array(‘exp‘,‘money + ‘ . $this->arr[‘money‘]));29         30         if($data = $this->d_user->lockTable($data)){31             $res = $this->user->save($data);32         }33         if($data2 = $this->d_user->lockTable($data2)){34             $res2 = $this->user->save($data2);35         }36         37         if($res && $res2){38             $this->user->commit();39             echo ‘commit‘;40         }else {41             $this->user->rollback();42             echo ‘rollback‘;43         }44     }45     46     /**47      * 支出方金钱是否满足48      */49     private function moneyFill($user, $id, $money){50         $current_money = $user->where(array(‘id‘ => $id))->getField(‘money‘);51         if($current_money < $money){52             echo ‘money no worth!‘;53             exit;54         }55     }56 }

 

 1 <?php 2 /** 3  * 用户表模型类 4  */ 5 class UserModel extends AdvModel{ 6      7     /** 8      * 乐观锁操作 9      */10     public function lockTable($res){11         12         //记录乐观锁13         $res = $this->recordLockVersion($res);14         15         //缓存当前线程的乐观锁16         $this->cacheLockVersion($res);17         18         //检查乐观锁并返回是否锁定19         return $this->checkLockVersion($res, $options);20     }21 }22 ?>

 

thinkphp继承高级model后的乐观锁运用(测试中)