Is it recommended to use a global variable for a PDO object?

0

Below I'll give you an example of how I use the PDO connection today to access my databases. I would like to see with you, whether it is a good practice this way, or whether it is recommended a safer and more efficient way.

For example:

<?php
require "environment.php";

global $pdo;

$config = array();
$config['options'] = array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 
UTF8");

if(ENVIRONMENT == "DEVELOPTMENT"){
    $config['dbname'] = '';
    $config['host'] = '';
    $config['user'] = '';
    $config['password'] = '';
} ELSE IF(ENVIRONMENT == "PRODUCTION"){
    $config['dbname'] = '';
    $config['host'] = '';
    $config['user'] = '';
    $config['password'] = '';
}

try{
    $pdo = new PDO("mysql:dbname=".$config['dbname'].";
    host=".$config['host'], $config['user'], $config['password'], 
    $config['options']);
}catch(PDOExcepetion $e){
    echo "ERRO: ".$e->getMessage();
    exit;
}

In the class I use this way:

<?php

class Categorias{
    public function getListaCategorias(){
        $array = array();
        global $pdo;

        $sql = $pdo->query("Select * from categorias");
        if($sql->rowCount() > 0){
            $array = $sql->fetchAll();
        }
        return $array;
    }
}
    
asked by anonymous 14.09.2018 / 16:33

1 answer

0

Short answer: Not recommended and should be avoided to the maximum!

Starting from the principle of unit tests, if you use this global variable you will never be able to mock your object.

To achieve this you should use dependency injection in the constructor of your class.

Example:

<?php

class Categorias{

    private $pdo;

    public function __construct($pdo) {
        $this->pdo = $pdo;
    }

    public function getListaCategorias(){
        $array = array();
        $sql = $this->pdo->query("Select * from categorias");
        if($sql->rowCount() > 0){
            $array = $sql->fetchAll();
        }
        return $array;
    }
}

You can read more about Mock and unit testing in this article and I highly recommend it:

Tests Unit 101: Mocks, Stubs, Spies and all those difficult words

I recommend reading SOLID principles by Robert Martin to guide your class design and avoid such decisions that can couple your classes:

SOLID Principles

In particular, read about the principle of DIP: Dependency Inversion Principle:

Dependency inversion principle

    
14.09.2018 / 16:49