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

Asked

Viewed 275 times

0

Below I will pass an example of how I use today the PDO connection to access my databases. I would like to see with you, if it is a good practice this way, or if 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 == "DEVELOPMENT"){
    $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;
}

Then in class I use it like this:

<?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;
    }
}

1 answer

3


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 must 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 nesee unit tests article that I highly recommend:

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

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

SOLID Principles

Read more about the DIP principle: Dependency Inversion Principle:

Dependency inversion principle

  • 1

    Thanks Leandro! I will read the articles you have indicated to me.

  • Please mark it as the correct one if possible and agree to my answer! Thanks @Welitonsernajotto

Browser other questions tagged

You are not signed in. Login or sign up in order to post.