Difference between #2 and #3 of
How to use nested DB transactions (MySQL 5+, PostgreSQL)

Revision #3 has been created by jonjonw on Apr 20, 2011, 10:55:26 PM with the memo:

Modified instructions to use a subclass rather than modifying framework code directly.
« previous (#2) next (#4) »

Changes

Title unchanged

How to use nested DB transactions (MySql 5+, PgSql)

Category unchanged

Tutorials

Yii version unchanged

Tags changed

db, mysql, postgresql, transaction, nested

Content changed


 
source code taken from: [PHP, PDO & Nested Transactions](http://www.kennynet.co.uk/2008/12/02/php-pdo-nested-transactions/)

tested with: MySql 5.1.30
[...]
Say there is service layer in an application, and one service may use others. No each service deals will complex business logic will needs to wrap that into transactions.

If there are services A and B here's how it might happen:
 


```php
[...]
But there's a solution:)

First, you'll need to extend PDO class
:
 
 and save it in your the protected/components directory: ```php class InsNestedPDO extends PDO {
// Database drivers that support SAVEPOINTs.
protected static $savepointTransactions = array("pgsql", "mysql");
[...]
```

Then, you'll need to alter
the behaviour of [CDbConnection::createPdoInstance()]. You can do this by making a subclass of it in protected/components/NestedDbConnection.php
 
 
There, change $pdoClass to your class name (InsNestedPDO in this example).
 
: ```php class NestedDbConnection extends CDbConnection
 
{
 
    
protected function createPdoInstance() {
 
    {
 
    
$pdoClass='InsPDO';
 
NestedPdo';
 
    
if(($pos=strpos($this->connectionString,':'))!==false)  {
 
   {
 
    
$driver=strtolower(substr($this->connectionString,0,$pos));      if($driver==='mssql' || $driver==='dblib')   $pdoClass='CMssqlPdoAdapter'; }
 
    }
 
    
return new $pdoClass($this->connectionString,$this->username,    $this->password,$this->_attributes);     }
 
} ``` It'd probably be better OOP to extend [CDbConnection], especially since createPdoInstance is protected. But then either there are inconsistencies with private/protected properties of [CDbConnection], or I didn't spent enough time to explore how to properly extend [CDbConnection].Note that $this->_attributes was also changed to $this->attributes so the subclassing will work.
 
 
Now you can add the class name to the db configuration array in protected/config/main.php
 
 
 
```php 
'db'=>array(
 
            'class'=>'NestedDbConnection',
 
            'connectionString' => ...
 
        ),
 
```
That's it, there you go;)
40 0
26 followers
Viewed: 46 416 times
Version: 1.1
Category: How-tos
Written by: mindeh
Last updated by: Boaz
Created on: Jun 30, 2009
Last updated: 2 years ago
Update Article

Revisions

View all history