Can you provide an example of how the Model, View, and Controller interact in a PHP application following the MVC pattern?
In a PHP application following the MVC pattern, the Model represents the data and business logic, the View displays the data to the user, and the Controller handles user input and updates the Model and View accordingly. An example of how they interact is when a user submits a form to update their profile information. The Controller receives the form data, updates the corresponding Model with the new information, and then instructs the View to display the updated profile to the user.
// Controller
class ProfileController {
public function updateProfile($formData) {
$profileModel = new ProfileModel();
$profileModel->updateProfile($formData);
$profileView = new ProfileView();
$profileView->displayProfile($profileModel->getProfile());
}
}
// Model
class ProfileModel {
private $profile;
public function updateProfile($formData) {
// Update profile data
$this->profile = $formData;
}
public function getProfile() {
return $this->profile;
}
}
// View
class ProfileView {
public function displayProfile($profile) {
// Display profile information to the user
echo "Name: " . $profile['name'] . "<br>";
echo "Email: " . $profile['email'] . "<br>";
}
}
// Usage
$profileController = new ProfileController();
$profileController->updateProfile($_POST);