在php中Controller向View传值

查看:287
本文介绍了在php中Controller向View传值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

想用MVC的方式写一个小的CMS,建立了Controller、Model、View,但是不知道Controller向view传值应该怎么写?

index.php

<?php
require('View/testView.php');
require('Model/testModel.class.php');
require('Controller/testController.class.php');
$testController = new testController();
$testController->show();
?>

testController.class.php

class testController{
    function show(){
        $testModel = new testModel();
        $data = $testModel->get();
        return $data;
    }
}

testModel.class.php

require('database.php');
get_connection();
class testModel{
    function get(){
        $sql = "SELECT * FROM db_problem";
        $res = mysql_query($sql);
        return $res;

    }
}

testView.php

<html>
<head>
    <meta charset="UTF-8">
    <title>BUG列表</title>
</head>
<body>
<table border="1px solid #bebebe" width="980px" cellpadding="1" cellspacing="0">
    <tr>
        <th width="10%">ID</th>
        <th width="70%">问题</th>
        <th width="20%">提交时间</th>
    </tr>
    <tr style="text-align: center">
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>
</body>
</html>

解决方案

首先你得在控制器里指定模版比如 $this->display('test'); 然后在display方法中把模版include进来就行了

如果想复杂一点,给模版增加语法糖,就在display中判断该模版是否有编译过后的文件,没有的话则执行编译(实质上就是正则替换,比如{$test}替换为$this->test),然后include编译后的文件

这样就可以直接使用控制器的变量了

之前写过一个简单的mvc框架,你可以参考一下,核心内容在钱158行https://github.com/eyblog/mvc...

这篇关于在php中Controller向View传值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆