Lets put the case that we’ve got two separate classes, each owns a mysqli object to use for database operations.
class A{
protected $mysqliObject;
public function __constructor(){
$this->mysqliObject=new mysqli(...)
}
public function doSomething(){
$this->mysqliObject->query(...);
}
}
class B{
protected $mysqliObject;
public function __constructor(){
$this->mysqliObject=new mysqli(...)
}
public function doSomething(){
$this->mysqliObject->query(...);
}
}
The doSomething() methods use the $mysqliObject for a database query (SELECT, UPDATE, DELETE, etc…). I want to do the following outside:
// Start point
$aObject=new A();
$bObject=new B();
$aObject->doSomething();
$bObject->doSomething();
// End point
…but I want to roll back both queries if any of them fails. How can I do that?
- Can I create a brand new
mysqliobject at “Start point”, and use it to commit or rollback at “End point” the database query ofclass Aandclass B? - Do I have to create outside, and pass the same
$mysqliObjectto the__constructor()ofclass Aandclass B, and use that to rollback or commit (outside).
Would like to see more techniques with pro-con’s.
Each database connection object you have represents a different connection to the database, even if the connection is to the same database server. Each connection is completely independent of each other, so a transaction started in one connection will be invisible to the other connection.
If all your database access is to the same server, then just create a single connection and pass it to anything that needs access to the connection. Then the transaction will be application-wide.
If you’re talking to different database servers, then you probably should wrap all the connections in an object that can coordinate the database activity. It will be that object’s responsibility to track which database connection has a transaction in flight.