問題描述
我剛剛進(jìn)入 MVC 設(shè)計(jì)模式.這里的一個(gè)簡單示例并沒有明確我對控制器使用的概念.能否請您解釋一下控制器的實(shí)際使用,同時(shí)保持簡單.
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.
型號(hào):
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 模式中控制器的目的是改變模型層的狀態(tài).
Controllers purpose in MVC pattern is to alter the state of model layer.
它是通過控制器接收用戶輸入來完成的(優(yōu)選 - 抽象為諸如 Request
實(shí)例之類的東西),然后根據(jù)從用戶輸入中提取的參數(shù),傳遞模型層適當(dāng)部分的值.
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.
與模型層的通信通常通過各種服務(wù)發(fā)生.反過來,這些服務(wù)負(fù)責(zé)管理持久性抽象和域/業(yè)務(wù)對象之間的交互,也稱為應(yīng)用程序邏輯".
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
}
控制者不負(fù)責(zé)什么?
MVC 架構(gòu)模式中的控制器不負(fù)責(zé):
- 初始化部分模型層
- 從模型層檢索數(shù)據(jù)
- 輸入驗(yàn)證
- 初始化視圖
- 選擇模板
- 創(chuàng)建響應(yīng)
- 訪問控制
- ...等
這篇關(guān)于MVC模式中使用PHP的控制器的目的是什么?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!