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

前端 未结 6 1638
醉梦人生
醉梦人生 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:27

    My advice is to avoid global in the bulk of the code - it's dangerous, hard to track and will bite you.

    The way that I'd do this is to have a function called getDB() which can either be at class level by way of a constructor injection or static within a common class.

    So the code becomes

    class SomeClass {
        protected $dbc;
    
        public function __construct($db) {
            $this->dbc = $db;
        }
    
        public function getDB() {
            return $this->dbc;
        }
    
        function read_something() {
            $db = getDB();
            $db->query();
        }
    }
    

    or using a common shared class.

    function read_something() {
        $db = System::getDB();
        $db->query();
    }
    

    No matter how much elegant system design you do, there are always a few items that are necessarily global in scope (such as DB, Session, Config), and I prefer to keep these as static methods in my System class.

    Having each class require a connection via the constructor is the best way of doing this, by best I mean most reliable and isolated.

    However be aware that using a common shared class to do this can impact on the ability to isolate fully the objects using it and also the ability to perform unit tests on these objects.

提交回复
热议问题