PHP中控制器(Controller)层的实现

控制器(Controller)的作用通常是在获取模型(Model)中数据并交给视图(View)去显示,那开发中我们应该如何去写呢?

1.创建Controller的类文件,我这里文件名为MatchController.class.php

<?php
/**
 * 比赛操作相关控制器功能类 
 */
class MatchController{
    /**
     * 比赛列表操作
     */
    public function listAction(){
        header('Content-Type: text/html;charset=utf-8');
        //实例化相应的模型类对象,调用某个方法,实现固定功能
        // require './MatchModel.class.php';
        // $m_match = new MatchModel();
        //通过工厂获得对象
        require './Factory.class.php';
        $m_match = Factory::M('MatchModel');
        $match_list = $m_match->getList();
        // $m_match2 = Factory::M('MatchModel');

        // 载入负责显示的html文件
        require './template/match_list_v.html';
    }
    /**
     * 比赛删除
     */
    public function removeAction(){
        
    }
}

2.在入口文件中实例化控制器对象(前端控制器或请求分发器),文件名index.php

为了能让index.php去执行我们要操作的动作,应该传给index.php一些参数,来告诉入口文件怎么做。
假如我们要在比赛列表(比赛Controller)中删除一条比赛信息,可以这样传参给index.php:

index.php?c=match&a=remove&id=N

相应的HTML文件应该这样写:

《PHP中控制器(Controller)层的实现》 通过点击事件给index.php传参

index.php:

<?php
//动作
$default_action = 'list';
$a = isset($_GET['a'])?$_GET['a']:$default_action;

//实例化控制器类
require './MatchController.class.php';
//实例化
$controller = new MatchController();
//调用方法
$action_name = $a.'Action';
$controller -> $action_name();//可变方法

《PHP中控制器(Controller)层的实现》

    原文作者:kangyiii
    原文地址: https://www.jianshu.com/p/bd50369c69a6
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞