jelgh
jelgh

Reputation: 706

Decoupling the database CODE for real

Im in a project creating a web application. Writing in php5.

As I was creating the user system (login, register new users and stuff) I all of a sudden had database code all over the place. Dont get me wrong, Im using a singleton database class with a single query function.

class MySQLDB {

    private staic $instance = null;
    private $config;
    private $connection = null;

    [...]

    public function query($query, $other_dbname = NULL) {
        $name = $this->config->dbname;
        if($other_dbname != NULL) {
            $name = $other_dbname;
        }

        mysql_select_db($name, $this->connection);
        $result = mysql_query($query);
        [...]
    }

So far so good. However, where to put the SQL-queries? I mean, in examples over the Internet you see Database queries in the authentication system making a strong coupling between the two totally different modules. What if we decide not to use a MySQL database? Then you dont only have to swap out the MySQLDB class with the connection and the query function but all parts of the whole web application with SQL-queries in them.

My solution was to have a MySQLQueryer static class next to the MySQLDB class. Where I keep and perform ALL the SQL querying. Like this register-a-new-user function:

public function register($user, $hash, $salt) {
    $user = mysql_real_escape_string($user);
    $query = "INSERT INTO users ( username, password, salt ) VALUES ( '$user' , '$hash' , '$salt' );";
    $ret = $this->db->query($query);

    return $ret;
}

Note that all the creation of hash and salt is done in the user authentication module (that is, not the database module).

Do you find this a good solution or are there better ones? For instance would it better to create a AuthenticationMySQLDatabaseHelper class with the above register function in it? That is, have each separate module have its own MySQLDatabaseHelper class to perform queries.

Maybe Im making the problem bigger than it is?

Upvotes: 2

Views: 937

Answers (1)

tonymarschall
tonymarschall

Reputation: 3882

As mentioned by biziclop: Have a look at

or other abstraction layers.

If you want to build something on your own it seems like a good start what you try todo.

Upvotes: 1

Related Questions