Saturday, January 5, 2013

Searching for an Elegant Transaction Strategy

Hey folks, how are you doing?

I´m adding transactions support to my project and the code structure is a bit ugly and repetitive, like in the pseudo-code below:

if ($this->request->data) {
$datasource = $this->User->getDataSource();
try {
$datasource->begin();
// save model X
$result = $this->X->save($this->request->data);

// if save went well, save unrelated model
if ($result) {
$yData = $this->Y->read(null, $y);
// set some properties in $yData
$result = $this->Y->save($yData);
}

if ($result) {
$datasource->commit();
} else {
$datasource->rollback();

$this->log("Error!\r\n $e");
$this->Session->setFlash('Error', 'default', array(), 'error');
}
}  catch (Exception $e) {
$datasource->rollback();

$this->log("Error!\r\n $e");
$this->Session->setFlash('Error', 'default', array(), 'error');
}
}

Things I dont like:
1. Check if save() succeeded
2. Duplicated code on $result == false and catch block

This code gets way simpler when I use saveAll() or saveAssociations() but some do this unrelated models saving;

This post is for me to get a grasp of what is your transaction strategy.
Do you wrap everything in a try/catch block?
Do you care if save succeded?
Do you have a better error handling strategy?
Do you use global or nested transactions?

Thanks for your time!
Luciano

--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
 
---
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com.
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com.
Visit this group at http://groups.google.com/group/cake-php?hl=en.
 
 

No comments: