使用PHP的MVC模式中的控制器的目的是什么? [英] What is the purpose of the controller in the MVC pattern using 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 \Components\Controller
{
private $recognition;
public function __construct(\Model\Services\Recognition $recognition)
{
$this->recognition = $recognition;
}
public function postLogin($request)
{
$this->recognition->authenticate(
$request->getParameter('credentials'),
$request->getParameter('method')
);
}
// other methods
}
不负责什么?
采用MVC架构模式的控制器不负责:
What is controller NOT responsible for?
Controllers in MVC architectural pattern are NOT responsible for:
- 初始化模型层的一部分
- 从模型层检索数据
- 输入验证
- 初始化视图
- 选择模板
- 创造回应
- 访问控制
- ..等等
这篇关于使用PHP的MVC模式中的控制器的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!