1

As of right now I have a database connection string included at the top of each of my pages. I'm then passing my database connection to the methods in my class like this:

public function select($db) {
  //Code here
}

Code on page:

$login_user->select($db);

My thought is that if I ever want to query a different database I can just create a new connection string in my include file called $db2 and then I just pass that value instead of $db.

Is this a standard way of doing this or do you have a different recommendation?

4
  • 1
    It is a frequently used solution if you might require an additional database connection, yes. Commented Nov 9, 2012 at 13:23
  • Ok, what if I was only going to ever use one database? Commented Nov 9, 2012 at 13:24
  • 2
    This is very primitive way. I suggest you to read about Dependency Injection: potstuck.com/2009/01/08/php-dependency-injection Commented Nov 9, 2012 at 13:24
  • Then you can save the effort for that argument for each function/method and use a static storage for the database object. Might be a global variable or some static member of some object always generated, maybe a singleton or something. Commented Nov 9, 2012 at 13:25

3 Answers 3

5

Passing a connection string to your classes has lots of disadvantages and no benefits. You are on the right track, but you want to pass the database object instead of a connection string.

Dependency Injection is a good way of giving your classes access to the database, which simply means to pass dependencies (ie database object) to the objects that need them, rather than the object itself obtaining the dependency from a global variable of some kind.

I would suggest that you use a method like setDb() on your classes to pass the database objects, and then store it as a property for any internal use.

For example, assuming you have created the database object $db in an initialisation script:

class SomeClass
{
    protected $db;

    public function setDb($db)
    {
        $this->db = $db;
    }

    public function something()
    {
        // do some query on the database using $this->db
    }
}

$obj = new SomeClass();
$obj->setDb($db);

$obj->something();

DI gives you the benefits that you mentioned: the ability to easily switch the db without having to do lots of work in your methods. There are other benefits, namely ease of testing.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, I ended up taking this approach and will expand into something like Thomas wrote below at a later time.
@MrCode as this answer is very old, do you still think this is the recommended way to pass the database connection to php classes? I'm stuck between this method and a pdo wrapper
should `setDb9() be a constructor? Also by set do you mean establish the connection? If so, how do I share that with derived classes?
@J.Doe Yes this is the still the recommended way (using a method or the constructor) because all the benefits remain such as being testable, and not tightly coupled.
@webNoob13 no, setDb() is a method. You can use the constructor instead if you like, to pass the database connection in. There are pros and cons: using the constructor reduces the code a bit but the method approach offers the most flexibility - you don't have to call it if you don't need it.
2

As already pointed out this is a very used approach. However, since you included the OOP tag I guess you are also looking for an OO view on the subject :). IMHO the problem with that approach is that you are using a string to represent something that has a meaning in your problem domain (the DB connection). One of the problems with doing this is that you can't delegate behavior to a string, so you end up handling things like connection errors in functions spread all over your system or in other objects that shouldn't care about it and actually have other responsibilities (as a rule of thumb I always try to stick to the SRP). Also, in case you generate documentation of your model (like UML diagrams) that DB connection will be a concept used in your system that won't be represented in the docs (since there is not a class to represent it). Finally, modeling the DB connection and its related DB access with an object is a quite used approach, see for example the Zend DB Adapter class.

HTH

Comments

2

Start by developing a class that handles everything to do with the database. Here is an example of a database class I started. It is not done but you could use it to pass in a different database, table, or whatever you want.

<?php
 class Database
 {      // BEGIN class database
     // variables
   protected $db_host;
   protected $db_user;
   protected $db_password;
   protected $db_name;
   protected $connection;
   protected $queryRun;
   protected $numRows;
   protected $seldb;

// constructor
function __constructor(){
}
public function connect($db_host,$db_user,$db_password,$db_name)
{
    $this->db_host = $db_host;
    $this->db_user = $db_user;
    $this->db_password = $db_password;
    $this->db_name = $db_name;
    $this->connection = mysql_connect($this->db_host,$this->db_user,$this >db_password);
    if(!$this->connection)
    {
        mysql_error();
    }
    $this->seldb = mysql_select_db($this->db_name,$this->connection);
    if(!$this->seldb)
    {
        mysql_error();  
    }
}
public function disconnect()
{
    mysql_close($this->connection);
}
public function query(){
    $this->queryRun = mysql_query($this->sql,$this->connection);
    return $this->queryRun;
}
public function select($table,$columns = '*',$where = null,$order = null,$sort = null)
{
    $this->sql = 'SELECT ' .$columns. ' FROM ' .$table;
    if($where != null)
    {
        $this->sql . ' WHERE ' . $where;
    }
    if($order != null)
    {
        $this->sql . ' ORDER ' . $order;
    }
    if($sort != null)
    {
        $this->sql . ' SORT BY ' . $sort; 
    }
}
public function insert($table,$columns,$updatecolumns,$where = null)
{
    $this->sql = 'INSERT INTO ' .$table. '(' .$columns. ') VALUES (' .$updatecolumns. ')';
    if($where != null)
    {
        $this->sql . ' WHERE ' . $where;
    }
}

public function outputQuery()
{
    if(!$this->queryRun)
    {
        echo "Error";
    }
    else {
        $numRows = mysql_fetch_array($this->queryRun);
        foreach($numRows as $rows)
        {
            echo "<div id='feeditem'>";
            echo "<a href='#'><textarea>";
            echo $rows;
            echo "</textarea></a>";
            echo "</div>";
        }
    }
}

  }
?>

Then you can create instances of the class and use whichever function in the class you need, when you need it.

<?php
    include 'database.class.php';
    database1 = new Database();
    database1->connect('127.0.0.1','root','','users');
?>

Something like this would be a good start.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.