自定义MVC框架-封装控制器基类

栏目: 后端 · 发布时间: 6年前

内容简介:上一章案例中,控制器中的查询方法调用模型查询到数据后,使用var_dump 函数输出数据下面改用视图输出数据,也就是使用html文件输出数据仍然使用smarty模板技术,为了使用方便,将smarty包拷贝到controller目录下

上一章案例中,控制器中的查询方法调用模型查询到数据后,使用var_dump 函数输出数据

下面改用视图输出数据,也就是使用html文件输出数据

仍然使用smarty模板技术,为了使用方便,将smarty包拷贝到controller目录下

修改UsersController类中的 selectAction 方法

public function selectAction()
    {
        require_once './model/UsersModel.class.php';
        $model = new UsersModel();
        $users = $model->users_getAll();
        //使用smarty渲染数据
        require_once './controller/smarty/Smarty.class.php';
        $smarty = new Smarty();
        $smarty->setTemplateDir("./view/");
        $this->smarty->assign("users", $users);
        $this->smarty->display("user_list.html");
    }

上面代码设置 view 目录为模板文件目录

在view目录下新建user_list.html,编写如下代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
<table>
    {foreach $users as $user}
    <tr>
        <td>{$user.username}</td>
        <td>{$user.pwd}</td>
        <td>{$user.realname}</td>
    </tr>
    {/foreach}
</table>
</body>
</html>

然后修改index.php 代码

require_once './controller/UsersController.class.php';
$c=new UsersController();
$c->selectAction();

访问index.php

自定义MVC框架-封装控制器基类

以同样的方式修改另外两个控制器类

修改完毕后发现有个问题,就是在每个控制器类的selectAction 方法中,都有如下重复代码

require_once './controller/smarty/Smarty.class.php';
        $smarty = new Smarty();
        $smarty->setTemplateDir("./view/");

随着控制器类的增多,重复代码会越来越多,维护起来很麻烦

解决方案:创建控制器基类,将上面代码封装到基类的构造函数中

class Controller{
    protected $smarty;
    public function __construct()
    {
        require_once './controller/smarty/Smarty.class.php';
        $smarty=new Smarty();
        $smarty->setTemplateDir("./view/");
        $this->smarty=$smarty;
    }
}

其他控制器类都继承此基类,以 UsersController.class.php 为例,最新代码如下

自定义MVC框架-封装控制器基类


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

失控

失控

[美] 凯文·凯利 / 东西文库 / 新星出版社 / 2010-12 / 88.00元

《失控》,全名为《失控:机器、社会与经济的新生物学》(Out of Control: The New Biology of Machines, Social Systems, and the Economic World)。 2006年,《长尾》作者克里斯·安德森在亚马逊网站上这样评价该书: “这可能是90年代最重要的一本书”,并且是“少有的一年比一年卖得好的书”。“尽管书中的一些例子......一起来看看 《失控》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具