MVC模式中使用PHP的控制器的目的是什么?
我刚刚进入 MVC 设计模式.这里的一个简单示例并没有明确我对控制器使用的概念.能否请您解释一下控制器的实际使用,同时保持简单.
I am just heading into MVC design pattern. A simple example here does not clear my concept about the use of controller. Could you please explain real use of controller while keeping it simple.
型号:
class Model {
public $text;
public function __construct() {
$this->text = 'Hello world!';
}
}
控制器:
class Controller {
private $model;
public function __construct(Model $model) {
$this->model = $model;
}
}
查看:
class View {
private $model;
//private $controller;
public function __construct(/*Controller $controller,*/ Model $model) {
//$this->controller = $controller;
$this->model = $model;
}
public function output() {
return '<h1>' . $this->model->text .'</h1>';
}
}
索引:
require_once('Model.php');
require_once('Controller.php');
require_once('View.php');
//initiate the triad
$model = new Model();
//It is important that the controller and the view share the model
//$controller = new Controller($model);
$view = new View(/*$controller,*/ $model);
echo $view->output();
推荐答案
MVC 模式中控制器的目的是改变模型层的状态.
Controllers purpose in MVC pattern is to alter the state of model layer.
它是通过控制器接收用户输入来完成的(优选 - 抽象为诸如 Request
实例之类的东西),然后根据从用户输入中提取的参数,传递模型层适当部分的值.
It's done by controller receiving user input (preferable - abstracted as some thing like Request
instance) and then, based on parameters that are extracted from the user input, passes the values to appropriate parts of model layer.
与模型层的通信通常通过各种服务发生.反过来,这些服务负责管理持久性抽象和域/业务对象之间的交互,也称为应用程序逻辑".
The communication with model layer usually happens via various services. These services in turn are responsible for governing the interaction between persistence abstraction and domain/business objects, or also called "application logic".
class Account extends ComponentsController
{
private $recognition;
public function __construct(ModelServicesRecognition $recognition)
{
$this->recognition = $recognition;
}
public function postLogin($request)
{
$this->recognition->authenticate(
$request->getParameter('credentials'),
$request->getParameter('method')
);
}
// other methods
}
控制者不负责什么?
MVC 架构模式中的控制器不负责:
- 初始化部分模型层
- 从模型层检索数据
- 输入验证
- 初始化视图
- 选择模板
- 创建响应
- 访问控制
- ...等
相关文章