I have a theoretical question that I hope someone can help me figure out.
I am currently writing a simple web application in PHP using the MVC design pattern. I have seen and read several manuals on this subject, but they are usually either too complicated or too simplified.
So, I currently have a simple User model:
class User { private $username; private $group;
I also have a simple Database class that implements this class:
interface DatabaseInterface { public function connect(); public function disconnect(); public function prepare($sql = null); public function execute($params = array()); public function rowCount(); public function fetch(); }
My question is: how to associate this Database class with the filling of the User class?
At the moment, I have another class called UserDAO , which is passed a reference to the Database class in its constructor, and it has a function called ValidateUser() , which then uses the interface methods described above to verify the user to the database.
class UserDAO { private $database; public function __construct($database) { $this->database = $database; } public function validateUser($username, $password) { $this->database->prepare('SELECT * FROM users WHERE...'); .... return true/false; } }
And now I pass the UserDAO object to the User class through the constructor, and also add another ValidateUser() method to the User class, which basically just calls the ValidateUser() method in the UserDAO > class.
New User class:
class User { private $username; private $group; //user, admin, etc private $userDAO; public function __construct($userDAO) { $this->userDAO = $userDAO; } public function validateUser($username, $password) { if($this->userDAO->validateUser($username, $password)) { // set stuff that i need return true; } return false; } // getters }
Something about this I don't like. Can someone help me understand how this process usually proceeds?
Also, the Database class usually remains static, so can I just call the connection using something like Database::instance() ? Now I create one database object at the top of the PHP page and pass it.
Feel free to leave me a comment if something is unclear, and I will try to fix it as soon as possible.
Thank you for watching and sorry for the length of the message.