I’ve recently started to work on an application based on the Kohana framework that has been in development for some months, and the code is not using any DB transactions. I’ve already seen data corruption because of this.
Going through all the code to add transactions manually would be a lengthy and error-prone task, so my plan is to implement something like the declarative transactions in the Java EE and Spring frameworks: simply wrap every controller action in a DB transaction using the before() and after() functions of the project-specific controller superclass. Maybe make it configurable via an overridable property containing the names of actions that require a transaction.
- Has this been done before in a reusable way?
- How can I deal with exceptions? Is after() called when an exception occurs? If so, how can I find out whether an exception was thrown? If not, how else can I react to them?
Using the
before()andafter()functions of the controller base class worked for many cases, but I felt uneasy about not doing an explicit rollback when dealing with exceptions. Then I found that I was also getting an implicit rollback whenever an action calledRequest::current()->redirect()because that function does anexit, soafter()never gets called.My new and improved solution is to override Kohana’s Request class, and I create a Kohana module so everyone can use it easily:
https://github.com/brazzy/kohana-transactional