Doctrine\DBAL\Connection::transactional PHP Метод

transactional() публичный Метод

The function gets passed this Connection instance as an (optional) parameter. If an exception occurs during execution of the function or transaction commit, the transaction is rolled back and the exception re-thrown.
public transactional ( Closur\Closure $func ) : mixed
$func Closur\Closure The function to execute transactionally.
Результат mixed The value returned by $func
    public function transactional(Closure $func)
    {
        $this->beginTransaction();
        try {
            $res = $func($this);
            $this->commit();
            return $res;
        } catch (Exception $e) {
            $this->rollBack();
            throw $e;
        } catch (Throwable $e) {
            $this->rollBack();
            throw $e;
        }
    }

Usage Example

 /**
  * @param string $endpointName
  *
  * @return int
  */
 public function fetchOrGenerateEndpointId($endpointName)
 {
     $endpointId = 0;
     $this->connection->transactional(function (Connection $connection) use($endpointName, &$endpointId) {
         $lookupHash = md5($endpointName);
         $endpointRecord = $connection->executeQuery("SELECT * FROM {$this->endpointsTableName} WHERE lookup_hash = ?", [hex2bin($lookupHash)])->fetch(\PDO::FETCH_ASSOC);
         if (!$endpointRecord) {
             $connection->insert($this->endpointsTableName, ['lookup_hash' => hex2bin($lookupHash), 'name' => $endpointName]);
             $endpointId = (int) $connection->lastInsertId();
         } else {
             $endpointId = (int) $endpointRecord['id'];
         }
     });
     return $endpointId;
 }
All Usage Examples Of Doctrine\DBAL\Connection::transactional