Created
February 3, 2016 11:58
-
-
Save IsraelOrtuno/308f3259daaec3515292 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Devio\Propertier; | |
use Throwable; | |
trait SavesUsingTransaction | |
{ | |
protected $savingTransaction = true; | |
public function save(array $options = []) | |
{ | |
if ($this->savingTransaction) { | |
return $this->saveWithinTransaction($options); | |
} | |
return parent::save($options); | |
} | |
public function saveWithinTransaction(array $options = []) | |
{ | |
$connection = $this->getConnection(); | |
$connection->beginTransaction(); | |
try { | |
if ($saved = parent::save($options)) { | |
$connection->commit(); | |
} else { | |
$connection->rollBack(); | |
} | |
return $saved; | |
} catch (Throwable $e) { | |
$connection->rollBack(); | |
throw $e; | |
} | |
} | |
public function savingTransaction($value) | |
{ | |
$this->savingTransaction = $value; | |
} | |
public function disableSavingTransaction() | |
{ | |
$this->savingTransaction = false; | |
} | |
public function enableSavingTransaction() | |
{ | |
$this->savingTransaction = true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment