编程思路
这次作业主要是通过模仿老师的mvc实现!
作业总结
对于mvc我主要是理解和模仿,mvc肯定能干很多事情,但是现在我想不出来太多。我目前是这样理解的:MVC=Model+View+Controller,model作为“后台”,view是“前台”,controller是“搬运工”!
MVC代码与效果图
- 模型model
<?php
//命名空间
namespace Mvc;
//模型类:用做数据库
class Model
{
public function getData()
{
return [
['id' => 1, 'name' => 'Dell电脑', 'model' => 'xps', 'price' => 15000],
['id' => 2, 'name' => '华为手机', 'model' => 'P30 Pro', 'price' => 4988],
['id' => 3, 'name' => '小爱同学', 'model' => 'AI音箱', 'price' => 299],
['id' => 4, 'name' => '小米电视', 'model' => '液晶电视', 'price' => 2399]
];
}
}
- 视图类view
<?php
namespace Mvc;
//视图类:渲染页面
class View
{
public function fetch($data)
{
$table = '<table>';
$table .= '<caption>有钱就买清单</caption>';
$table .= '<tr><td>ID</td><td>品名</td><td>型号</td><td>价格</td></tr>';
foreach ($data as $good) {
$table .= '<tr>';
$table .= '<td>' . $good['id'] . '</td>';
$table .= '<td>' . $good['name'] . '</td>';
$table .= '<td>' . $good['model'] . '</td>';
$table .= '<td>' . $good['price'] . '</td>';
$table .= '</tr>';
}
$table .= '</table>';
return $table;
}
}
echo '<style>
table {border-collapse: collapse; border: 1px solid; width: 500px;height: 150px}
caption {font-size: 1.2rem; margin-bottom: 10px;}
tr:first-of-type { background-color:lightblue;}
td,th {border: 1px solid}
td:first-of-type {text-align: center}
</style>';
- 控制器类controller
<?php
//控制器:将商品展示出来
namespace Mvc;
//1.加载模型类
require 'Model.php';
//2.加载视图类
require 'View.php';
//3.创建控制器类
class Controller
{
//模型对象
private $model;
//视图对象
private $view;
//构造方法,作为外部对象注入点
public function __construct($model,$view)
{
$this->model = $model;
$this->view = $view;
}
public function index()
{
//1.获取数据
$data = $this->model->getData();
//2.渲染模板
return $this->view->fetch($data);
}
}
//4.客户端调用
$model = new Model;
$view = new View;
//实例化控制器类
//构造方法作为注入点,实现对外部以来对象的共享
$contorller = new Controller($model,$view);
echo $contorller->index();
- 效果图