I'm learning MVC (and indeed OOP) and finding the examples online great for basic overview but when I get into the nuts and bolts of a complex project I'm coming a bit unstuck.
I've setout a basic 'User' model below. What I'm wondering is at what point does a Model have too many responsibilities? And when this happens what are the options? Should you have sub models - e.g. UserLoginModel instead of an all encompassing User Model?
PS cannot seem to paste the code so it will all stay in code block - sorry about that.
//USER MODEL
class UserModel {
private $userId;
private $userName;
private $address
private $email
private $password;
/**
* Some instance of a DB class
*/
private $db;
/**
* Some encryption class which can generate cipher text
*/
private $encryption;
public function __construct($databaseClass){
//some database layer like a table gateway
$this->db = $databaseClass;
//some encryption class which can be used to test a password against a cipher
$this->enc = $encryptionClass;
}
/*
GETTERS/SETTERS...
*/
public function findUser($username){
// 1. Find user in database
// 2. Map database array to properties
// 3. Return boolean
}
public function validateLogin($password){
// 1. Turn $pasword into cipher text using $this->enc class
// 2. Match User object password
// 3. Return boolean
}
public function updateUser($data){
//some code for updating the user
}
public function deleteUser($user){
//code for deleting user
}
}
//Authentication controller - receives request /AuthController/doLogin
class AuthController {
public function doLogin(){
$db = new databaseClass(); //e.g. a tablegateway
$encryptionClass = new encryptionClass(); //some class which generates ciphers
$user = new UserModel($db);
if($user->findUser($_POST['username'])){
$loginSuccess = $user->validateLogin($_POST['password']);
//do stuff
}
}
}
The model is the central component of the design pattern. It expresses the application's behavior in terms of the problem domain, independent of the user interface. It directly manages the data, logic and rules of the application.
All the functions and responsibilities must have in Model.
The Controller accepts input and converts it to commands for the model or view. It will get the function and/or methods by the Model.
And the View can be any output representation of information, or input of data by user.
StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.