phalcon 事务处理

来源:互联网 发布:js正则表达式exec 编辑:程序博客网 时间:2024/04/29 00:14

单独的事务
单独事务在一个新的连接中执行所有的SQL,虚拟外键检查和业务规则与主数据库连接是相互独立的。 这种事务需要一个事务管理器来全局的管理每一个事务,保证他们在请求结束前能正确的回滚或者提交。
example1

use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;use Phalcon\Mvc\Model\Transaction\Manager as TxManager;try {    // Create a transaction manager    $manager     = new TxManager();    // Request a transaction    $transaction = $manager->get();    $robot              = new Robots();    $robot->setTransaction($transaction);    $robot->name        = "WALL·E";    $robot->created_at  = date("Y-m-d");    if ($robot->save() == false) {        $transaction->rollback("Cannot save robot");    }    $robotPart              = new RobotParts();    $robotPart->setTransaction($transaction);    $robotPart->robots_id   = $robot->id;    $robotPart->type        = "head";    if ($robotPart->save() == false) {        $transaction->rollback("Cannot save robot part");    }    // Everything's gone fine, let's commit the transaction    $transaction->commit();} catch (TxFailed $e) {    echo "Failed, reason: ", $e->getMessage();}

自定义事务
example2
如果一个应用只用到了一个数据库连接并且这些事务都不太复杂,那么可以通过简单的将当前数据库连接设置成事务模式实现事务功能,根据操作的成功与否提交或者回滚:

<?phpuse Phalcon\Mvc\Controller;class RobotsController extends Controller{    public function saveAction()    {        // Start a transaction        $this->db->begin();        $robot              = new Robots();        $robot->name        = "WALL·E";        $robot->created_at  = date("Y-m-d");        // The model failed to save, so rollback the transaction        if ($robot->save() == false) {            $this->db->rollback();            return;        }        $robotPart            = new RobotParts();        $robotPart->robots_id = $robot->id;        $robotPart->type      = "head";        // The model failed to save, so rollback the transaction        if ($robotPart->save() == false) {            $this->db->rollback();            return;        }        // Commit the transaction        $this->db->commit();    }}
0 0
原创粉丝点击