What is the best way to connect / connect a database to a function in PHP?

Parameter pair:

$connection = {my db connection/object}; function PassedIn($connection) { ... } function PassedByReference(&$connection) { ... } function UsingGlobal() { global $connection; ... } 

So, passed, passed by reference or using global. I think about the functions that are used in only one project, which will have only 1 database connection. If there are multiple connections, it is definitely passed or passed by reference.

I ask that you don’t need to pass the link when you are in PHP5 using an object, and then transferring or using global capabilities.

The reason I'm asking is because I am tired of always inserting $ connection into my function parameters.

+4
source share
6 answers

I use the Singleton ResourceManager class to handle things like DB connections and configuration settings through an entire application:

 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 the / objects / functions 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 is an interesting question here about when to actually use this type of class.

+4
source

Try creating code in an object-oriented manner. Methods that use the database must be grouped into a class, and the class instance must contain a connection to the database as a class variable. Thus, a database connection is available for functions that need it, but this is not global.

 class MyClass { protected $_db; public function __construct($db) { $this->_db = $db; } public function doSomething() { $this->_db->query(...); } } 
+2
source

I see that many people have proposed some kind of static variable.

Essentially, there are very few differences between a global variable and a static variable. With the exception of syntax, they have exactly the same characteristics. This way you are not gaining anything by replacing the global variable with a static variable. In most examples, there is a level of isolation in that a static variable is not passed directly, but rather through a static method (for example, a single or static registry). Although this is slightly better, it still has global challenges. If you ever need to use more than one database connection in your application, you will be screwed. If you ever want to know which parts of your code have side effects, you need to manually check the implementation. This is not something that will make or break your application, but it will make it difficult to maintain.

I suggest choosing one of the following options:

  • Pass the instance as arguments to the functions that it needs. This is by far the simplest, and it has all the advantages of a narrow scale, but can become quite cumbersome. It is also a source for dependency injection, as some parts of your code can become intermediaries. If this happens, go to.

  • Place the instance in the scope of the object in which there is a method that it needs. For instance. if the Foo->doStuff() method requires a database connection, pass it in the Foo constructor and set it as a protected instance variable to Foo . You may still encounter some problems associated with passing in a method, but this is usually not a problem with bulky constructors than with methods. If your application gets large enough, you can use the dependency injection container to automate this.

+2
source

My advice is to avoid being global in the amount of code - this is dangerous, difficult to track and will bite you.

What I will do is to have a function called getDB (), which can either be at the class level, either by embedding the constructor, or from a static within the general 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 common class.

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

No matter how elegant the design of the system you are doing, there are always several elements that are necessarily global in volume (for example, DB, Session, Config), and I prefer to store them as static methods in my System class.

Each class requires a connection through the constructor, this is the best way to do this, I would best mention the most reliable and isolated ones.

However, keep in mind that using a common general class for this can affect the ability to completely isolate objects that use it, as well as the ability to perform unit tests for these objects.

+1
source

None of the above.

All mysql functions can use the database connection argument. If you leave this argument, the last mysql_connect () connection is assumed.

0
source
 function usingFunc() { $connection = getConnection(); ... } function getConnection() { static $connectionObject = null; if ($connectionObject == null) { $connectionObject = connectFoo("whatever","connection","method","you","choose"); } return $connectionObject; } 

This way, the static $ connectionObject is maintained between getConnection calls.

-1
source

All Articles