views:

102

answers:

3

I built myself a MySQL class which I use in all my projects. I'm about to start a project that is heavily based on user accounts and I plan on building my own class for this aswell. The thing is, a lot of the methods in the user class will be MySQL queries and methods from the MySQL class.

For example, I have a method in my user class to update someone's password:

class user() {
    function updatePassword($usrName, $newPass)
    {
        $con = mysql_connect('db_host', 'db_user', 'db_pass');
        $sql = "UPDATE users SET password = '$newPass' WHERE username = '$userName'";
        $res = mysql_query($sql, $con);
        if($res) return true;
        mysql_close($con);
    }
}

(I kind of rushed this so excuse any syntax errors :) )

As you can see that would use MySQL to update a users password, but without using my MySQL class, is this correct? I see no way in which I can use my MySQL class within my users class without it seeming dirty. Do I just use it the normal way like $DB = new DB();? That would mean including my mysql.class.php somewhere too...

I'm quite confused about this, so any help would be appreciated, thanks.

+2  A: 

You should explore dependency injection (PHP example)

John Conde
A: 

Study up on extending a class. Or in other words, inheritance.

jjclarkson
In this case, extending the class would be the wrong approach. Logically a user has nothing to do with a database.
Felix Kling
Thanks for the links. I somewhat knew about class extensions before, but not sure if it's good to use in this case? I don't really want to extend my MySQL class to include user functions, or extend my user class to include MySQL functions, or perhaps there's something I'm missing? :P --- EDIT: Felix got there before me, thanks for the help though :)
Joe
+1  A: 

Yes you have to include the mysql.class.php in order to use the class. But this is similar as in Java, Python, etc. You have to specify what you use.

One way to make the class available in your user class would be to call the constructor with an instance of the DB class:

class User {
    private $_db;
    public function __construct($db) {
        $this->_db = $db;
    }

    public function updatePassword($usrName, $newPass) {
        // use $this->_db here
    }

}

and then:

require 'mysql.class.php'

$user = new User(new DB());
$user->updatePAssword('foo', 'bar');
Felix Kling
Very good example, thanks. I'll wait a while to see other peoples answers before I pick one :)
Joe
+1, good answer
stereofrog