一、MVG概念(摘取)
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑
MVC 是一种使用 MVC(Model View Controller 模型-视图-控制器)设计创建 Web 应用程序的模式:
MVC 模式同时提供了对 HTML、CSS 和 JavaScript 的完全控制
二、实践理论(摘取)
开发模式
smarty
将压缩包解压后,将libs 文件夹拷贝到项目的根目录下,并重命名为 smarty,然后在控制器类中引入 Smarty.class.php
三、实际代码
创建模型类 NewsModel.php
<?php class NewsModel { function list() { $dns = "mysql:host=localhost;dbname=test"; $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(‘news.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[‘c‘]; // 获取请求的方法名称 $a=$_GET[‘a‘]; // 创建控制器类的对象 $ctrl=new $c(); // 调用请求的方法 $ctrl->$a();
说明:这个 index.php 有一个专业的名词:入口文件
地址栏中输入如下地址方法
http://localhost/index.php?c=newscontroller&a=index
后续上传详细自我理解
原文:https://www.cnblogs.com/Rawan/p/11986325.html