0

I read many posts and blogs about Singleton and database connection. What I understand from the singleton definition is that you can use it on any class object that is instantiated many times while staying intact. I have a web application, and I was wondering if I could implement Singleton for database connection

Here is what I have under the DatabaseGateway class:

class DatabaseGateway
{
    private $DBConnection;
    private $serverName;
    private $userName;
    private $password;
    private $databaseName;

    public function __construct() {
       //not done
    }

    public function getDBConnection() {
        return $this->DBConnection;
    }

    public function openDBConnection() {
        $this->DBConnection = new mysqli($this->serverName, $this->userName, $this->password, $this->databaseName);
    }

    public function closeDBConnection() {
        mysqli_close($this->DBConnection);
    }

The method OpenDBConnection is used when users log in in the UserGateway class. I was wondering if it is a good idea, and if it possible, to make openDBconnection into a singleton, while everyone has their own account and password.

  • https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – Sammitch Oct 31 '17 at 19:00
  • Singletons are generally frowned upon, but there's no risk of collision between users if that's what you're getting at. Even singletons only exist for the life of one request. I.e., if two different users make two different requests, they're going to each get their own singleton. – Alex Howansky Oct 31 '17 at 19:03
  • So in a web app where there can be different users with different user/passwords, it is not possible to implement singleton? Does it only work when there is 1 account/password for everyone? thanks – david benalal Oct 31 '17 at 19:04
  • It is certainly _possible_ to implement a singleton pattern, regardless of how many users there are. However, singletons _in general_ are not recommended. See the link @Sammitch posted for why. – Alex Howansky Oct 31 '17 at 19:11
  • But my teacher wants me to implement one. That's why I was wondering if it is possible to do it for database connection. I guess I'll never do it in real life – david benalal Oct 31 '17 at 19:15

0 Answers0