MVC 模式代表 Model-View-Controller(模型-视图-控制器) 模式。这种模式用于应用程序的分层开发。
- Model(模型) - 模型代表一个存取数据的对象。它也可以带有逻辑,在数据变化时更新控制器。
- View(视图) - 视图代表模型包含的数据的可视化。
- Controller(控制器) - 控制器作用于模型和视图上。它控制数据流向模型对象,并在数据变化时更新视图。它使视图与模型分离开。
Model:
class Student{
private $stuNo;
private $name;
function setStuNo($stuNo){
$this->stuNo=$stuNo;
}
function getStuNo(){
return $this->stuNo;
}
function setName($name){
$this->name=$name;
}
function getName(){
return $this->name;
}
}
View:
class StudentView{
function printDetail($stuNo,$name){
echo 'student--',PHP_EOL;
echo "student no:$stuNo",PHP_EOL;
echo "name:$name",PHP_EOL;
}
}
Controller:
class StudentControl{
private $model;
private $view;
function __construct($model,$view){
$this->model=$model;//关键代码
$this->view=$view;//关键代码
}
function setStudentStuNo($stuNo){
$this->model->setStuNo($stuNo);
}
function getStudentStuNo(){
return $this->model->getStuNo();
}
function setStudentName($name){
$this->model->setName($name);
}
function getStudentName(){
return $this->model->getName();
}
function updateView(){
$this->view->printDetail($this->model->getStuNo(), $this->model->getName());
}
}
Client:
/*
演示:
*/
echo '设置学生信息:',PHP_EOL;
$model=new Student;
$model->setStuNo(10);
$model->setName('Robert');
$view=new StudentView;
$controller=new StudentControl($model,$view);
$controller->updateView();
$model->setStuNo(11);
$model->setName('John');
echo '更新学生信息后:',PHP_EOL;
$controller->updateView();
运行结果:
设置学生信息:
student--
student no:10
name:Robert
更新学生信息后:
student--
student no:11
name:John