Note that there are some explanatory texts on larger screens.

plurals
  1. PODecoupling the database CODE for real
    text
    copied!<p>Im in a project creating a web application. Writing in php5. </p> <p>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. </p> <pre><code>class MySQLDB { private staic $instance = null; private $config; private $connection = null; [...] public function query($query, $other_dbname = NULL) { $name = $this-&gt;config-&gt;dbname; if($other_dbname != NULL) { $name = $other_dbname; } mysql_select_db($name, $this-&gt;connection); $result = mysql_query($query); [...] } </code></pre> <p>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. </p> <p>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:</p> <pre><code>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-&gt;db-&gt;query($query); return $ret; } </code></pre> <p>Note that all the creation of hash and salt is done in the user authentication module (that is, not the database module).</p> <p><strong>Do you find this a good solution or are there better ones?</strong> 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. </p> <p>Maybe Im making the problem bigger than it is?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload