我尝试使用 ChatGPT 深入了解 MVC 设计各个步骤的核心。我特别尝试了解哪个实例在何时何地执行什么操作。我最终列出了 13 个基本点。
我很清楚该列表没有考虑到无数的中间步骤。
虽然ChatGPT很有趣,但我想向一些在世的专家询问一下这个列表: 该列表是否包含根本性错误?是否包含所有基本步骤?有什么意见欢迎留言!
这是列表和一些 PHP 代码:
## Step 1: The Front Controller receives the request.
$request = $_SERVER['REQUEST_URI']; // "/index.php/user/read/42"
## Step 2: The Front Controller instantiates the Router.
$router = new Router();
## Step 3: The Front Controller passes the request to the Router.
$router->dispatch($request);
class Router {
private $controller = "UserController";
private $action = "read";
private $id = 42;
public function getController() {
return $this->controller;
}
public function getAction() {
return $this->action;
}
public function getId() {
return $this->id;
}
public function dispatch($request) {
## Step 4: The Router recieves the request and extracts controller name, action, and id from it.
// logic to set $this->controller, $this->action, and $this->id based on $request
$tmp = explode('/', $request);
$this->controller = ucfirst($tmp[2]).'Controller';
$this->action = $tmp[3];
$this->id = $tmp[4];
## Step 5: The Router determines which Controller to use to handle the request.
$controllerName = $this->getController(); // returns "UserController"
## Step 6: The Router instantiates the chosen Controller.
$controller = new $controllerName(); // instantiates the UserController
## Step 7: The Router calls the appropriate action on the Controller.
$action = $this->getAction(); // returns "read"
$userId = $this->getId(); // returns 42
$controller->$action($userId); // calls UserController->read(42)
}
}
class UserController {
public function read($id) {
## Step 8: The Controller instantiates the Model.
$model = new UserModel();
## Step 9: The Controller calls the appropriate action on the Model to get user data.
$userData = $model->readUser($id);
// logic to process $data
## Step 11: The Controller instantiates the View.
$view = new UserView();
## Step 12: The Controller passes the processed data to the View.
$view->render($userData);
}
public function update($id) {
$model = new UserModel();
$userData = $model->updateUser($id);
$view = new UserView();
$view->render($userData);
}
}
class UserModel {
public function readUser($id) {
## Step 10: The Model retrieves data from the database, then returns it to the Controller.
// database logic to get user
$userData = ['id' => 42, 'given_name' => 'John', 'family_name' => 'Dow']; // placeholder
return $userData;
}
public function updateUser($id) {
// database logic to update user
$updatedUserData = ['id' => 42, 'given_name' => 'John', 'family_name' => 'Dow']; // placeholder
return $updatedUserData;
}
}
class UserView {
public function render($userData) {
## Step 13: The View renders the page for the user based on the data received from the Controller.
// display logic using $userData
echo implode('<br>', $userData);
}
}