zoukankan      html  css  js  c++  java
  • 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 ?>
  • 相关阅读:
    Hibernate框架做数据库操作
    Spring AOP几个相关术语复习梳理
    Unknown initial character set index '255' received from server...
    使用IDEA的activiti时报错:发现了以元素 'process' 开头的无效内容...
    获取Class实例的4种方式
    maven设置全局和局部jdk版本
    JSP的9大内置对象和4大域对象(作用域)
    oracle中NVL,NVL2,NULLIF,COALESCE等函数
    MIME类型
    Eclipse集成Tomcat,并发布Web工程
  • 原文地址:https://www.cnblogs.com/kingfly/p/4018089.html
Copyright © 2011-2022 走看看