How to make a database connection using the Singleton project pattern

2

Well I do a lot of web applications, where all of them I use database, and every time I go to do a new project, I create a file responsible for doing the queries with the database (CRUD).

I just want to change this, I want to make a file where I have all this queries with the database, and I wanted to use the Singleton project pattern.

And I wanted some help on how to mount this file.

    
asked by anonymous 07.08.2014 / 17:41

2 answers

5

The Singleton pattern consists of always returning the same instance of a particular class at any point in the application.

This is limited access to the constructor method and returning the instance through a static method, that is, a method that you can call without instantiating the class.

A quick implementation follows:

class BancoDeDados
{
    // Instância da classe
    private static $instance = null;
    private $conn;

    // Construtor privado: só a própria classe pode invocá-lo
    private function __construct()
    {
        $host = "localhost";
        $user = "root";
        $pswd = "root";
        $db = "banco";

        try {
            $this->conn = mysqli_connect($host, $user, $pswd, $db);
            $this->conn->set_charset('utf8');
        } catch (Exception $e) {
            die("Erro na conexão com MySQL! " . $e->getMessage());
        }
    }

    // método estático
    static function getInstance()
    {
        // Já existe uma instância?
        if (self::$instance == NULL)
            self::$instance = new BancoDeDados();   // Não existe, cria a instância 
        return self::$instance;                     // Já existe, simplesmente retorna
    }

    // Previne o uso de clone
    private function __clone() {}
}

// Usando a classe
$db = BancoDeDados::getInstance();

// Você não poderá fazer isso por causa do construtor privado:
$db = new BancoDeDados();

From there, develop the methods for accessing your bank class.

    
07.08.2014 / 18:06
5
  

Singleton

     

Intention:

     

Ensure a single instance and provide a global access point   to it throughout the application usage cycle

First, singleton is not for database use. If you need to use multiple databases, what happens? Singleton becomes a problem. If you need pattern to database , search for DAO (for example) . And if you do not use it yet, try working with PDO on PHP , as it is much safer, more flexible and serves well.

Second, singleton in PHP is impracticable. The reason? At every request http made PHP automatically destroys all instances. Whatever the language or technology used, any situation in which the response destroys the instance singleton ceases to make sense, because a new instance is generated for each request.

When using a pattern you need to understand well what problem it intends to solve if it fits the resolution of your problem and whether the environment in which you will apply it will allow that purpose to be fulfilled. Anything other than this you should avoid using, as opposed to solving your problem it will end up creating many more.

    
08.08.2014 / 09:17