Phalcon \ Mvc \ Model - 回滚失败的交易

The code:

class myModel extends Phalcon\Mvc\Model
{
    public function beforeSave()
    {
        $this->getDi()->getShared('db')->begin();
    }
    ...
    public function afterSave()
    {
        $this->getDi()->getShared('db')->commit();
    }
}

My question is - what happens if along the way, between beforeSave() and afterSave() there's an Exception thrown - how can I cleanly roll back the transaction? Where should I stick $this->getDi()->getShared('db')->rollback(); in to?

Thanks!

I'd recommend overloading the save() method entirely.

Here's my example with transactions. Note that you won't need transactions if you're not going to implement additional logic here (like removing related models)

/**
 * Delete old relations before saving new ones
 */
public function save($data=null, $whiteList=null)
{
    $db = $this->getDI()->get('db');

    try
    {
        // Start transaction
        $db->begin();

        // ... Do some additional work. Remove related models etc...

        // Update model
        if (!parent::save($data, $whiteList))
            throw new \Exception('Cannot save the model');

        $db->commit();
    }
    catch (\Exception $e)
    {
        $db->rollback();

        $this->appendMessage(new \Phalcon\Mvc\Model\Message($e->getMessage(), '', 'error', $this));
        return false;
    }
    return true;
}