文档
Welcome! 安装(Installation) 示例列表(List of examples) 依赖注入与服务定位器(Dependency Injection/Service Location) MVC 架构(The MVC Architecture) 使用控制器(Using Controllers) 使用模型(Working with Models) 模型元数据(Models Meta-Data) 事务管理(Model Transactions) Phalcon 查询语言(Phalcon Query Language (PHQL)) 缓存对象关系映射(Caching in the ORM) 对象文档映射 ODM (Object-Document Mapper) 使用视图(Using Views) 视图助手(View Helpers) 资源文件管理(Assets Management) Volt 模版引擎(Volt: Template Engine) MVC 应用(MVC Applications) 路由(Routing) 调度控制器(Dispatching Controllers) 微应用(Micro Applications) 使用命名空间(Working with Namespaces) 事件管理器(Events Manager) 请求环境 (Request Environment) 返回响应(Returning Responses) Cookie 管理(Cookies Management) 生成 URL 和 路径(Generating URLs and Paths) 闪存消息(Flashing Messages) 使用 Session 存储数据(Storing data in Session) 过滤与清理(Filtering and Sanitizing) 上下文编码(Contextual Escaping) 验证(Validation) 表单(Forms) 读取配置(Reading Configurations) 分页(Pagination) 使用缓存提高性能(Improving Performance with Cache) 安全(Security) 加密/解密( Encryption/Decryption ) 访问控制列表 ACL(Access Control Lists ACL) 多语言支持(Multi-lingual Support) 通用类加载器 ( Universal Class Loader ) 日志记录(Logging) 注释解析器(Annotations Parser) 命令行应用(Command Line Applications) 队列(Queueing) 数据库抽象层(Database Abstraction Layer) 国际化(Internationalization) 数据库迁移(Database Migrations) 调试应用程序(Debugging Applications) Phalcon 开发工具(Phalcon Developer Tools) 提高性能:下一步该做什么?(Increasing Performance: What's next?) 单元测试(Unit testing) 授权(License)
教程

发布于 2015-08-21 15:13:30 | 1406 次阅读 | 评论: 0 | 来源: 网络整理

事务管理(Model Transactions)

当一个进程执行多个数据库操作时,通常需要每一步都是成功完成以便保证数据完整性。事务可以确保在数据提交到数据库保存之前所有数据库操作都成功执行。

Phalcon中通过事务,可以在所有操作都成功执行之后提交到服务器,或者当有错误发生时回滚所有的操作。

自定义事务(Manual Transactions)

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

<?php

use PhalconMvcController;

class RobotsController extends Controller
{
    public function saveAction()
    {
        $this->db->begin();

        $robot              = new Robots();
        $robot->name        = "WALL·E";
        $robot->created_at  = date("Y-m-d");

        if ($robot->save() == false) {
            $this->db->rollback();
            return;
        }

        $robotPart            = new RobotParts();
        $robotPart->robots_id = $robot->id;
        $robotPart->type      = "head";

        if ($robotPart->save() == false) {
            $this->db->rollback();
            return;
        }

        $this->db->commit();
    }
}

隐含的事务(Implicit Transactions)

也可以通过已有的关系来存储记录以及其相关记录,这种操作将隐式的创建一个事务来保证所有数据能够正确的保存:

<?php

$robotPart          = new RobotParts();
$robotPart->type    = "head";

$robot              = new Robots();
$robot->name        = "WALL·E";
$robot->created_at  = date("Y-m-d");
$robot->robotPart   = $robotPart;

$robot->save(); // Creates an implicit transaction to store both records

单独的事务(Isolated Transactions)

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

<?php

use PhalconMvcModelTransactionFailed as TxFailed;
use PhalconMvcModelTransactionManager 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 goes fine, let's commit the transaction
    $transaction->commit();

} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

事务可以用以保证以一致性的方式删除多条记录:

<?php

use PhalconMvcModelTransactionFailed as TxFailed;
use PhalconMvcModelTransactionManager as TxManager;

try {

    // Create a transaction manager
    $manager     = new TxManager();

    // Request a transaction
    $transaction = $manager->get();

    // Get the robots will be deleted
    foreach (Robots::find("type = 'mechanical'") as $robot) {
        $robot->setTransaction($transaction);
        if ($robot->delete() == false) {
            // Something goes wrong, we should to rollback the transaction
            foreach ($robot->getMessages() as $message) {
                $transaction->rollback($message->getMessage());
            }
        }
    }

    // Everything goes fine, let's commit the transaction
    $transaction->commit();

    echo "Robots were deleted successfully!";

} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

事务对象可以重用,不管事务对象是在什么地方获取的。只有当一个commit()或者一个rollback()执行时才会创建一个新的事务对象。可以通过服务容器在整个应用中来创建和管理全局师傅管理器。

<?php

use PhalconMvcModelTransactionManager as TransactionManager

$di->setShared('transactions', function () {
    return new TransactionManager();
});

然后在控制器或者视图中访问:

<?php

use PhalconMvcController;

class ProductsController extends Controller
{
    public function saveAction()
    {
        // Obtain the TransactionsManager from the services container
        $manager     = $this->di->getTransactions();

        // Or
        $manager     = $this->transactions;

        // Request a transaction
        $transaction = $manager->get();

        // ...
    }
}

While a transaction is active, the transaction manager will always return the same transaction across the application.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务