Your pretty close. Instead of making specific CreateUser class though, I would more than likely create something a little more generic.
class User
{
private $db;
private $id;
private $username;
private $password;
public function __construct(MySql $db, $id = 0) {
$this->db = $db;
$this->id = $id;
if ($this->id != 0) {
$results = $this->db->query("
SELECT username, password FROM users WHERE id = '{$this->id}'
");
if ($results) {
$this->username = $results->username;
$this->password = $results->password;
}
}
}
public function setUsername($name) {
$this->username = $name;
return $this;
}
public function setPassword($pass) {
$this->password = $pass;
return $this;
}
public function getUserName() {
return $this->username;
}
public function getPassword() {
return $this->password;
}
public function save() {
if ($this->id = 0) {
$id = $this->db->query("
INSERT INTO users (username, password
) VALUES (
'{$this->username}', '{$this->password}'
");
$this->id = $id;
} else {
$this->db->query("
UPDATE users
SET username = '{$this->username}', password = '{$this->password}'
WHERE id = '{$this->id}'
");
}
return $this->id;
}
}
You can then use this to create and retrieve users.
$user = new User(new Mysql);
$user->setUsername('thorpe');
$user->setPassword('dontbecrazy');
$id = $user->save();
echo "New user {$user->getUsername()} created with an id of $id";
And to get user 101.
$user = new User(new Mysql, 101);
echo $user->getUsername();
Of course there is allot of things missing in this example, but this is a basic model. You would want to ensure that your database class itself takes care of sanitizing data, and you would very much want to have it implement some interface or Abstract class.