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' => 300
17         );
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 ?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM