问题
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