標籤:style blog color io ar sp div art on
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後的樂觀鎖運用(測試中)