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

2022-12-07,,,,

 <?php
class IndexAction extends Action {
private $d_user;
private $user;
private $arr; public function __construct(){
parent::__construct();
$this->d_user = D('User');
$this->user = M('user'); //打款的配置信息
$this->arr = array(
'userA' => 1,
'userB' => 2,
'money' => 300
);
} /**
* 打款逻辑(事务操作)
*/
public function index(){
$this->user->startTrans();
$this->moneyFill($this->user, $this->arr['userA'], $this->arr['money']); $data = array('id' => $this->arr['userA'], 'money' => array('exp','money - ' . $this->arr['money']));
$data2 = array('id' => $this->arr['userB'], 'money' => array('exp','money + ' . $this->arr['money'])); if($data = $this->d_user->lockTable($data)){
$res = $this->user->save($data);
}
if($data2 = $this->d_user->lockTable($data2)){
$res2 = $this->user->save($data2);
} if($res && $res2){
$this->user->commit();
echo 'commit';
}else {
$this->user->rollback();
echo 'rollback';
}
} /**
* 支出方金钱是否满足
*/
private function moneyFill($user, $id, $money){
$current_money = $user->where(array('id' => $id))->getField('money');
if($current_money < $money){
echo 'money no worth!';
exit;
}
}
}
 <?php
/**
* 用户表模型类
*/
class UserModel extends AdvModel{ /**
* 乐观锁操作
*/
public function lockTable($res){ //记录乐观锁
$res = $this->recordLockVersion($res); //缓存当前线程的乐观锁
$this->cacheLockVersion($res); //检查乐观锁并返回是否锁定
return $this->checkLockVersion($res, $options);
}
}
?>

thinkphp继承高级model后的乐观锁运用(测试中)的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。