phalcon 事务处理

本文介绍了Phalcon框架中如何进行事务处理,包括单独事务和自定义事务的实现方式,强调了事务管理器在确保事务正确回滚或提交中的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单独的事务
单独事务在一个新的连接中执行所有的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
如果一个应用只用到了一个数据库连接并且这些事务都不太复杂,那么可以通过简单的将当前数据库连接设置成事务模式实现事务功能,根据操作的成功与否提交或者回滚:

<?php

use 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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值