Smutty
MVC Framework
ClassSmutty_Model_Transaction
This class provides an easy way of grouping related models together when saving data. As an example, say you're writing a bug tracker and you want people to be able to update bugs with comments. Well, these comments will probably involve adding a new record to the comments table, and possibly changing the bug information in the bug table. So you're going to want to change multiple tables with a single action (many more examples of needing to change more than one table can be easily imagined).
This is where the Smutty_Model_Transaction class comes to help. All you need to do it set up your models as you want them to be saved, and then add them to an instance of the this class. You can then control saving and error handling of multiple classes with one object!
function saveCommentAction( $data, &$session ) {
$bug = Bug::find( $data->int('id') );
$bug->status_id = $data->int( 'bug_status' );
$comment = new Bug_Comment();
$comment->fill();
$trans = new Smutty_Model_Transaction();
$trans->add( $bug );
$trans->add( $comment );
if ( $trans->save() )
$this->redirect(array( controller => 'bug' ));
else
$this->signalError( $trans->getErrors() );
}
You can see that by using the transaction object we've put all the validating and error collecting code in one place so we can handle it as one thing.
Transactions and Loops
One very important thing to note when using this class is that it stores references to your models, so changes made to them are fed back to your controller. This means however that you need to take special care if doing certain things like the following.
$trans = new Smutty_Model_Transaction();
foreach ( $args as $arg ) {
$post = new Post();
$trans->add( $post );
unset( $post );
}
$trans->save();
The VERY important thing to note here is the use of unset() at the end of the loop. If this is ommitted then you could get some very strange results you weren't expecting. This is due to how PHP handles references, not an implementation detail of Smutty.
Links: Post a comment