Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method for getting a database connection/object into a function in PHP?

Tags:

database

php

A couple of the options are:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) { ... }

function UsingGlobal() {
    global $connection;
    ...
}

So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.

I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.

The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.

like image 894
Darryl Hein Avatar asked Mar 02 '23 06:03

Darryl Hein


1 Answers

I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:

class ResourceManager {
    private static $DB;
    private static $Config;

    public static function get($resource, $options = false) {
        if (property_exists('ResourceManager', $resource)) {
            if (empty(self::$$resource)) {
                self::_init_resource($resource, $options);
            }
            if (!empty(self::$$resource)) {
                return self::$$resource;
            }
        }
        return null;
    }

    private static function _init_resource($resource, $options = null) {
        if ($resource == 'DB') {
            $dsn = 'mysql:host=localhost';
            $username = 'my_username';
            $password = 'p4ssw0rd';
            try {
                self::$DB = new PDO($dsn, $username, $password);
            } catch (PDOException $e) {
                echo 'Connection failed: ' . $e->getMessage();
            }
        } elseif (class_exists($resource) && property_exists('ResourceManager', $resource)) {
            self::$$resource = new $resource($options);
        }
    }
}

And then in functions / objects / where ever:

function doDBThingy() {
    $db = ResourceManager::get('DB');
    if ($db) {
        $stmt = $db->prepare('SELECT * FROM `table`');
        etc...
    }
}

I use it to store messages, error messages and warnings, as well as global variables. There's an interesting question here on when to actually use this type of class.

like image 157
Jrgns Avatar answered Apr 08 '23 03:04

Jrgns