MVC

1.MVC

1.1概念
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑
MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:
Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。通常模型对象负责在数据库中存取数据。
View(视图)是应用程序中处理数据显示的部分。通常视图是依据模型数据创建的。
Controller(控制器)是应用程序中处理用户交互的部分。通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。
1.2 实践

smarty

将压缩包解压后,将libs 文件夹拷贝到项目的根目录下,并重命名为 smarty,然后在控制器类中引入 Smarty.class.php

创建模型类 NewsModel.php

<?php
class NewsModel
{
    function list() {
        $dns = "mysql:host=localhost;dbname=school";
        $user = 'root';
        $password = 'root';
        $pdo = new PDO($dns, $user, $password);
        $res = $pdo->query("select * from news");
        $news = $res->fetchAll(PDO::FETCH_ASSOC);
        return $news;
    }
}

创建控制器类,NewsController.php

<?php
include 'smarty/Smarty.class.php';
include 'NewsModel.php';
class NewsController
{
    // 显示所有的新闻数据
    public function index()
    {
        // 创建NewsModel类的对象
        $model = new NewsModel();
        $news = $model->list();
        // 创建Smarty 类的对象
        $smarty = new Smarty();
        $smarty->assign("news", $news);
        // 读取news.html文件的源代码,并发送给浏览器
        $smarty->display('list.html');
    }
}

list.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.css" rel="stylesheet">
</head>
<body>
  <div class="container">   
  <table class="table">
    <tr>
      <th>编号</th>
      <th>标题</th>
      <th>创建时间</th>
    </tr>
   {foreach $news as $item}
   <tr>
     <td>{$item['id']}</td>
     <td>{$item['title']}</td>
     <td>{$item['create_time']}</td>
   </tr>
   {/foreach}
  </table>
  </div>
</body>
</html>

在浏览中要直接访问控制器,因为控制器是模型与视图的桥梁

控制器负责调用模型中的方法,查询数据
控制器将模型中返回的数据分配给视图
但是我们无法在浏览器中直接访问某个控制器类中的具体方法

解决方案

在项目的根目录下,新建一个 index.php

在这个文件中,获取用户想要访问的控制器和方法名称,并进行调用

<?php
include 'NewsController.php';
// 获取请求的控制器名称
$c=$_GET['NewsController'];
// 获取请求的方法名称
$a=$_GET['index'];
// 创建控制器类的对象
$ctrl=new $c();
// 调用请求的方法
$ctrl->$a();

说明:这个 index.php 有一个专业的名词:入口文件

地址栏中输入如下地址方法

http://localhost/index.php?c=newscontroller&a=index

assign(“news”, $news); 变量赋值

$smarty->display(‘list.html’);读取news.html文件的源代码,并发送给浏览器

$news = $res->fetchAll(PDO::FETCH_ASSOC);返回一个包含结果集中所有行的数组

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值