Let's say I have this model. (I made it very simple for demonstration purposes.)
class User
{
public $id;
public $email;
public $password;
public $errors = [];
public function isValid()
{
if (strpos($this->email, '@') === false) {
$this->errors['email'] = 'Please enter an email address';
}
// ...
return !$this->errors;
}
}
And let's say I have this DAO for retrieving, adding, updating, and deleting users.
class UserDAO
{
public function getUsers() { ... }
public function getUserById($id) { ... }
public function addUser(User $user) { ... }
public function updateUser(User $user) { ... }
public function deleteUser($id) { ... }
public function isEmailUnique($email) { ... }
}
When I process a form, I typically do something like this:
$userDAO = new UserDAO();
$user = new User();
$user->email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user->password = filter_input(INPUT_POST, 'password');
if ($user->isValid()) {
if ($userDAO->addUser($user)) {
// ...
} else {
// ...
}
} else {
// do something with $user->errors
}
Now, let's say part of my user validation should be to check whether email is unique, how do I make it part of the User model? So that, when $user->isValid()
is called, it also checks whether the email is unique? Or am I doing this all wrong?
From my weak understanding of DAOs, DAOs are responsible for all interactions with the database. So how do I make the model work with database from within?