如何在 Kohana / PHP 中优雅地管理数据库事务
我是 Kohana 的新手,但有 Spring/Java 背景。
在 Spring 中,我习惯了自动将数据库事务应用于所有服务方法。我只是标记该方法以指示它是否只需要读取事务或读/写。
Kohana 中人们在这方面做了什么?我正在使用的一个新应用程序没有交易,除非在他们知道有必要的几个地方手动进行。对我来说这似乎有点冒险,很容易忽视一些事务一致性要求,在 Spring 中全局强制执行这一点总是很好。
I'm new to Kohana but come from a Spring/Java background.
In Spring I'm used to all service methods automatically having DB transactions applied to them. I just tag the method to indicate whether it only needs a read transaction or read/write.
What do people do in this regard in Kohana? A new app I'm working with doesn't have transactions except manually in a few places where they know it's necessary. To me this seems a bit risky, it's easy to overlook some transactional consistency requirement, it was always nice to have that globally enforced in Spring.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在Kohana中,事务需要手动完成,没有办法像Spring中那样。
您可以在下面找到一些处理方法:
使用
数据库
方法:使用查询生成器:
In Kohana transactions need to be done manually, there is no way to do it like in Spring.
Below you can find some ways how to deal with it:
Using
Database
methods:Using Query Builder:
我创建了一个 Kohana 模块(受 Spring 启发),使使用事务变得更加容易:
https://github .com/brazzy/kohana-transactional
添加模块后,只需添加
到控制器即可,所有操作都会在事务内自动执行,当操作因异常失败时会回滚。在我看来,这是最有用的实现,因为在 PHP 项目中拥有单独的服务层似乎并不常见。
我最终可能会实现对只读事务的支持(如果可以以独立于供应商的方式实现)。
I've created a Kohana module (inspired by Spring) that makes using transactions a lot easier:
https://github.com/brazzy/kohana-transactional
After adding the module, you can just add
to the controller, and all actions are automatically executed inside a transaction, which is rolled back when the action fails with an exception. This seemed to me to be the most useful implementation, as having a separate service layer doesn't seem to be common in PHP projects.
I may eventually implement support for read-only transactions (if it's possible to do in a vendor-independant way).
以下是我的处理方法:
为所有服务方法类创建一个基类:
创建一个包含所有“受保护”函数的子类:
调用服务方法:
它将显示:“start test commit”
这里的技巧是你必须对所有函数使用“protected”,否则它将不再运行(它将调用直接“测试”函数,而不是通过 __call()。
Here is how I deal with it:
Create a base class for all service method classes:
Create a child class with all "protected" functions:
Call service method:
It will display: "start test commit"
The trick here is you will have to use "protected" for all your functions, if not it will no longer run (it will call the "test" function directly, not through __call().
根据您的个人情况手动进行:
Do it by Hand and for your individual situations: