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

前端 未结 6 1656
醉梦人生
醉梦人生 2020-12-05 16:59

A couple of the options are:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) {         


        
6条回答
  •  孤街浪徒
    2020-12-05 17:38

    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.

提交回复
热议问题