Skip to content

Commit

Permalink
Using custom Statement class, to support this type of flow: $stmt = $…
Browse files Browse the repository at this point in the history
…db->prepare(); $db->multiAtomic(function() use ($stmt) { $stmt->execute(); });
  • Loading branch information
crocodile2u committed Jun 22, 2017
1 parent 92384a2 commit 7ea6178
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
4 changes: 3 additions & 1 deletion lib/Db.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ function __construct($dsn, $user = null, $password = null, array $options = [])
$this->dsn = $dsn;
$this->user = $user;
$this->password = $password;
$options[\PDO::ATTR_STATEMENT_CLASS] = [Statement::class, [$this]];
$this->options = $options;
$this->id = self::$nextId++;
$this->queryCount = 0;
Expand Down Expand Up @@ -194,6 +195,7 @@ public function prepare($statement, array $driver_options = array())
{
$timer = $this->debugLog("prepare");
$this->beginTransactionIfNeeded();
/** @var Statement $ret */
$ret = $this->getPdo()->prepare($statement, $driver_options);
$this->queryCount++;
$this->debugTimerEnd($timer, "prepare(): " . $statement);
Expand Down Expand Up @@ -329,7 +331,7 @@ public function emulateRollback()
$this->shouldStartTransaction = false;
}

protected function beginTransactionIfNeeded()
public function beginTransactionIfNeeded()
{
if ($this->shouldStartTransaction) {
$this->debugLog("Actually starting a transaction");
Expand Down
20 changes: 20 additions & 0 deletions lib/Statement.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace tinyorm;

class Statement extends \PDOStatement
{
/** @var Db */
private $db;

protected function __construct(Db $db)
{
$this->db = $db;
}

function execute($input_parameters = null)
{
$this->db->beginTransactionIfNeeded();
return parent::execute($input_parameters);
}
}

0 comments on commit 7ea6178

Please sign in to comment.