如何使用SLIM框架创建MySQL事务


How to create MySQL transaction using SLIM framework

我正在使用Slim框架来创建RESTful API。我如何创建一个事务来执行多个SQL语句和/或能够回滚一些这些语句?

SLIM不附带MySQL,所以基本上你会这样做的正常方式,与PDO或MySQLi,所以基本上(假设PDO)你正在寻找:

$db->beginTransaction();

其中$db是你用来使用MySQL的PDO连接对象,参见手册

但是,在调用PDO::commit

之前,事务中的任何内容都不会运行。
$db->commit();

之后可以调用PDO::rollBack

$db->rollBack();

Slim中间件可以解决这个问题。您可以创建一个精简的中间件,在操作之前打开事务,然后提交。像这样:

class TransactionMiddleware {
  private $db;
  public function __construct(PDO $db) {
    $this->db = $db;
  }
  public function __invoke($request, $response, $next){
    try{
        $this->db->beginTransaction();
        $response = $next($request, $response);
        $this->db->commit();
    } catch(PDOException $pdoe) {
        $db->rollBack();
        throw $pdoe;
    }
    return $response;
  }}

那么你可以在路由操作中使用这个类:

//$db is a PDO reference 
$tx = new TransactionMiddleware($db);
//action is a method in MyController class to respond to '/' route
$app->post('/', ''MyController:action')->add($tx);

我建议您阅读瘦身中间件文档:https://www.slimframework.com/docs/concepts/middleware.html .