I have a singleton DataBase class to connect to a database:
class DataBase { private static $mysqli; final private function __construct() {} public static function getInstance() { if (!is_object(self::$mysqli)) self::$mysqli = new mysqli($H,$U,$P,$B); return self::$mysqli; } private function __destruct() { if (self::$mysqli) self::$mysqli->close(); } private function __clone() {} }
I use this singleton from many other classes and extract the database connection from the constructor function, for example:
class Customer { public $db; function __construct() { $this->db=DataBase::getInstance(); } public function create() { $this->db->query('INSERT INTO customers SET ... WHERE id=100');
and
class Product { public $db; function __construct() { $this->db=DataBase::getInstance(); } public function create() { $this->db->query('INSERT INTO products SET ... WHERE id=200');
Since all my classes actually use the same connection defined by the singleton class, my question is: can I start a database transaction from one class and roll back / copy it from another class. What I really mean by this is the code below a correctly made db transaction to create a Customer and Product (classes modeling db records behind) within a single database transaction:
$Customer=new Customer(); $Customer->db->begin_transaction(); ... $Customer->create(); ... $Product=new Product(); $Product->create(); ... $Product->db->commit();
How will this code work in a multi-user environment where all users use the same connection from the sigleton class?
source share