Using singletons in PHP is considered bad practice. In my experience, the unit test is the most problematic one. It is hard to make sure that the two tests are independent when testing single numbers.
I would delegate responsibility for the restriction "only one instance must exist" for the code as the Db object creates.
He is also looking for me since you do not understand Singletons in PHP. If you have 10,000 simultaneous requests, each request is executed in a separate process or thread, that is, everyone will have their own "singleton" instance.
They are not a "connection pool" in PHP, but you can use mysqli persistent connections. This can be achieved by passing p: in front of the host name when building mysqli. This may help here, but handle it with caution ( meaning to read the documentation first )
However, just for theory, a singleton in PHP should be aware that someone can use clone . The meaning in your case could be made like this:
$db = DB::getInstance(); $db2 = clone $db;
To avoid this, apply the __clone() method as follows:
public function __clone() { throw new Exception("Can't clone a singleton"); }
However, this was only for theory, I would recommend that you reorganize the class and throw away the Singleton pattern.
source share