1、Magento事务处理使用方法

Mangeto中执行某个功能时,如update、insert、delete,magento的model会自动对事务进行处理。这些写操作都集中到 model的save方法或者delete方法来处理,执行时候会调用resource model的beginTransaction方法来开启事务,调用resource model的commit方法来提交事务,调用resource model的rollBack方法来回滚事务。save方法代码如下:

public function save()
{
    /**
    * Direct deleted items to delete method
    */
    if($this->isDeleted()){
        return $this->delete();
    }

    if(!$this->_hasModelChanged()){
        return $this;
    }

    $this->_getResource()->beginTransaction();//开启事务
    $dataCommited = false;
    try{
        $this->_beforeSave();
        if($this->_dataSaveAllowed){
            $this->_getResource()->save($this);
            $this->_afterSave();
        }
        $this->_getResource()->addCommitCallback(array($this, 'afterCommitCallback'))->commit();//添加提交后的回调函数
        $this->_hasDataChanges = false;
        $dataCommited = true;
    }catch(Exception $e){
        $this->_getResource()->rollBack();//异常时事务回滚
        $this->_hasDataChanges = true;
        throw $e;
    }
    if($dataCommited){
        $this->_afterSaveCommit();
    }
    return $this;
}

delete方法和save类似,这里就不贴代码出来分析了。

results matching ""

    No results matching ""