As a side note I want to point out that MVC does not mean create a Model class, a Controller class, and a View class. It means separation of concerns, where the important bits are Model (Business Logic) and View (Presentation Logic). The Controller is the part that binds these two together.
A simple (W)MVC example would be a contact page:
// contact.php
if (isset($_POST['submit'])) {
mail('
[email protected]', $_POST['subject'], $_POST['message']);
}
include 'views/contact.html';Believe it or not, but this is really an (W)MVC implementation.
Where:
- contact.php -- is the controller (model and view are unaware of each other, yet together they achieve a specific goal, contacting the owner)
- mail() -- is the model (hiding how mailing works and providing a simple interface)
- views/contact.html -- is the view (hiding the interface how the user will enter the required data)
- Apache -- is the frontController (like your App.php, translate a route to a controller)
It's important that the model is unaware of the view and the controller otherwise it would severely limit it's re-use.
Your LoginModel is also not correct because it violates the Single Responsibility Principle. It finds a user based on user and pass, and it stores a session cookie. You'll also have to duplicate the "find a user based on user and pass" every time you need it thus violating the Don't Repeat Yourself principle.
class UserMapper .. {
private $pdo;
function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
function findByNameAndPassword($username, $password) {
// implementation
}
}
class Session .. {
function set($key, $value, $lifetime) {
// implementation
}
function get($key, $default = null) {
// implementation
}
}
class LoginService {
private $userMapper;
private $session;
function login($username, $password) {
// $user = $this->userMapper->findByNameAndPassword($username, $password);
// if (null !== $user) {
// $this->session->set('loggedin', true, 86400);
// }
}
function isLoggedIn() {
return $this->session->get('loggedin', false);
}
}As an example. You would use the LoginService in your controller as it hides how a user is logged in and is completely re-usable in another project if needed. Controller and View are considered to be project specific and thus (mostly) throw-away-code. The Model however not so much.
This kind of programming will help keep your controllers thin and your (model) code re-usable.