What are the key components of MVC (Model-View-Controller) and how do they interact in PHP development?
The key components of MVC are: 1. Model: Represents the data and business logic of the application. 2. View: Represents the presentation layer of the application. 3. Controller: Acts as an intermediary between the Model and View, handling user input and updating the Model accordingly. In PHP development, these components interact as follows: - The Controller receives user input, processes it, and updates the Model. - The Model holds the data and business logic of the application. - The View then fetches data from the Model and presents it to the user.
// Example PHP code implementing MVC
// Model
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
// View
class UserView {
public function output($user) {
return "User name: " . $user->name;
}
}
// Controller
class UserController {
public function getUser() {
$model = new User("John Doe");
$view = new UserView();
return $view->output($model);
}
}
// Implementation
$controller = new UserController();
echo $controller->getUser();