How to create MySQL transaction using SLIM framework

╄→尐↘猪︶ㄣ 提交于 2019-12-24 01:48:16

问题


I am using the Slim framework to create a RESTful API. How can I create a transaction to execute multiple SQL statements and/or to be able to rollback some of those statements?


回答1:


SLIM doesn't come with MySQL attached, so basically you'd do it the normal way, with either PDO or MySQLi, so basically (assuming PDO) you're looking for:

$db->beginTransaction();

where $db is the PDO connection object you're using to use MySQL, see the manual

However nothing from the transaction is run until you call PDO::commit

$db->commit();

after which you can call PDO::rollBack

$db->rollBack();

if anything has gone wrong.




回答2:


A Slim middleware could be solution to this problem. You can create a slim middleware to open a transaction before your operation, and commit after all. Something like that :

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;
  }}

Than you can use this class in route action:

//$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);

I sugest you read the slim middleware docs : https://www.slimframework.com/docs/concepts/middleware.html .



来源:https://stackoverflow.com/questions/25483386/how-to-create-mysql-transaction-using-slim-framework

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!