I'm trying to improve some PHP scripts using a OO design (it's procedural now with some OO parts). Just to be clear, I'm not trying to build a full MVC application, but I am trying to seperate parts as much as possible. I've never used MVC before in PHP (only a little bit in Java).
When using Google, I find 100 different MVC approaches for PHP and I can't find a good book on this subject. If anyone could suggest me a good book on OO design in PHP, it would be much appreciated.
Currently, a part to add a user to the database (assuming a user only contains a firstname for now), looks like this (users.php):
$validator = new UserValidator();
if ($validator->validate($_POST['user_firstname']))
$result = $db->execute("INSERT INTO `users` (`user_firstname`) VALUES (?)", $_POST['user_firstname']);
Knowing that adding users may be done at multiple places and I don't want code repeat, I will create a usermodel. This class will contain a method addUser(). The thing I'm a bit stuck with is the validation. The UserValidator will check if all fields are filled in correctly.
I could do this:
$validator = new UserValidator();
if ($validator->validate($_POST['user_firstname']))
$result = $user->addUser($_POST['user_firstname']);
But I could also do this:
$result = $user->adduser($_POST['user_firstname'];
Now the User-class will contain the validator and the addUser()-method will perform this validation. Assuming the above code is the controller, what option is the best? Delegating the validation functionality to the model or doing it in the controller?
The same problem applies when getting information of a certain user. Not everyone may get this info, so my code could look like this:
if ($user->hasAccess($_SESSION['id'], $_GET['id'])
$user->getUserById($_GET'id']);
(The hasAccess()-method will check if the user who is logged in can view details of a certain user id)
But I could also just call getUserById() and check if you have access in that method. Which option is the best?
Thank you!