Bub*_*oza -1 php model-view-controller
我刚刚进入MVC设计模式.这里的一个简单示例并不清楚我对控制器使用的概念.你能否解释一下控制器的实际用途,同时保持简单.
模型:
class Model {
public $text;
public function __construct() {
$this->text = 'Hello world!';
}
}
Run Code Online (Sandbox Code Playgroud)
控制器:
class Controller {
private $model;
public function __construct(Model $model) {
$this->model = $model;
}
}
Run Code Online (Sandbox Code Playgroud)
视图:
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>';
}
}
Run Code Online (Sandbox Code Playgroud)
指数:
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();
Run Code Online (Sandbox Code Playgroud)
MVC模式中的控制器目的是改变模型层的状态.
它由控制器接收用户输入(最好 - 抽象为像Request
实例之类的东西)完成,然后,根据从用户输入中提取的参数,将值传递给模型层的适当部分.
与模型层的通信通常通过各种服务进行.反过来,这些服务负责管理持久性抽象和域/业务对象之间的交互,或者也称为"应用程序逻辑".
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
}
Run Code Online (Sandbox Code Playgroud)
MVC架构模式中的控制器不负责: