登录  /  注册
博主信息
博文 48
粉丝 0
评论 0
访问量 38912
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
单例模式、工厂模式、注册树及MVC学习—2018年09月07日22时000分
小星的博客
原创
656人浏览过

这回课程涉及了几种常见的设计模式,随后通过简单例子讲解了MVC模式的原理及实现方式。

重要知识点:

1. 单例模式:单例模式的创建实例方法要设置成静态的。

                     要将构造方法( __construct()  )及克隆方法( __clone()  )进行私有化,杜绝外部实例化类。

2. 工厂模式:就是一个批量创建对象的方法,较易理解。

3. 注册树:就是将预定义好的类挂到树上,即放到一个容器中(一般是数组)的概念。

4. MVC模式是个比较重要的概念,核心在与将数据,视图与业务逻辑分开。


  1. 单例模式

    一个类只能实例化一次,就是不能从外部进行实例化,

    代码实例:

    实例

    class Config
    {
        //这里是静态的,这样可以通过类来访问
        private static $instance = null;
    
        //不允许从外部实例化类,因此这里要禁止构造方法
        //只需要将构造方法私有化就行了
        private function __construct()
        {
        }
        //把克隆方法私有化,防止外部复制来进行实例化
        private function __clone()
        {
        }
        //外部仅允许通过一个公共静态方法来创建实例
        public static function getInstance()
        {
            if(self::$instance == null){
                self::$instance = new self();
            }
            return self::$instance;
        }
    
        private $setting;
        public function set()
        {
            if(func_num_args() > 0){
                switch (func_num_args())
                {
                    case 1:
                        if(is_array(func_get_arg(0))) {
                            $this->setting = func_get_arg(0);
                        }
                        break;
                    case 2:
                        $this->setting[func_get_arg(0)] = func_get_arg(1);
                        break;
                    default: echo '传入参数格式错误!!!';
                }
            }else{
                echo '没有参数!!!';
    
            }
        }
        public function get($name='')
        {
            if(empty($name)) {
                return $this->setting;
            }
            return $this->setting[$name];
    
        }
    }
    $ins1 = Config::getInstance();
    $ins2 = Config::getInstance();
    //$ins = new Config();//这里是不能创建对象的
    var_dump($ins1,$ins2);
    echo '<hr>';
    $ins1->set('host','127.0.0.1');
    print_r($ins1->get());

    运行实例 »

    点击 "运行实例" 按钮查看在线实例


  2. 工厂模式

    代码实例:

    实例

    <?php
    /**
     * 工厂类,不使用new,而是用函数/方法批量创建对象
     */
    
    class Factory
    {
        public static function create($type, $size=[])
        {
            switch($type)
            {
                case 'rectangle':
                    return new Rectangle($size[0],$size[1]);
                    break;
                case 'trangle':
                    return new Rectangle($size[0],$size[1]);
                    break;
            }
        }
    }
    //长方形类
    class Rectangle
    {
    
        private $width;
        private $height;
    
        public function __construct($width, $height)
        {
            $this->width = $width;
            $this->height = $height;
        }
    
        public function area()
        {
            return $this->width * $this->height;
        }
    }
    // 声明一个三角形类
    class Rriangle
    {
        private $bottom; // 底
        private $height; // 高
        public function __construct($bottom, $height)
        {
            $this->bottom = $bottom;
            $this->height = $height;
        }
        //计算面积
        public function area()
        {
            return ($this->bottom * $this->height)/2;
        }
    }
    
    echo (Factory::create('rectangle',['10','10']))->area();

    运行实例 »

    点击 "运行实例" 按钮查看在线实例


  3. 注册树

    代码实例:

    实例

    <?php
    /**
     * 注册树: 就是创建一个对象集合/对象池/对象树,对象容器来存储对象
     */
    class Demo1{};
    class Demo2{};
    class Demo3{};
    
    class Register
    {
        public static $objs;
    
        public static function set($index,$obj)
        {
            self::$objs[$index] = $obj;
        }
        public static function get($index)
        {
            return self::$objs[$index];
    
        }
        public static function del($index)
        {
            unset(self::$objs[$index]);
    
        }
    }
    
    Register::set('demo1',new Demo1());
    Register::del('demo1');
    var_dump(Register::get('demo1'));

    运行实例 »

    点击 "运行实例" 按钮查看在线实例


  4. MVC模式设计

    mvc是指Model(模型),View(视图),Controller控制器()。

    原理:浏览器发出请求发送至controlle中,model中通过数据库访问拿到数据返回给controller,然后将数据渲染到view中,然后将生成好的html文件返回给浏览器。

    首先是Model类,该类中放数据库连接及拿数据的操作:

    实例

    <?php
    /**
     * 模型类
     */
    
    namespace mvc\model;
    
    class Model
    {
        public $pdo = null;
        public $result = [];
    
        //连接数据库
        public function __construct($dsn, $user, $pass)
        {
            $this->pdo = new \PDO($dsn, $user, $pass);
    
        }
        public function select($table, $num)
        {
            $stmt = $this->pdo->prepare("SELECT `id`,`name`,`age`,`salary` FROM {$table} LIMIT :num");
            $stmt->bindValue(':num', $num, \PDO::PARAM_INT);
            $stmt->execute();
            $this->result = $stmt->fetchAll(\PDO::FETCH_ASSOC);
            return $this->result;
    
        }
    
    }

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

    接下来是View,类中设计一个模板:

    实例

    <?php
    namespace mvc\view;
    
    class View
    {
        public $data = [];
        public function __construct($data)
        {
            $this->data = $data;
        }
        //获取数据
        public function getData()
        {
            return $this->data;
        }
        public function display($data)
        {
            $table = '<!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>MVC简介</title>
        <style>
            table,th,td{border:1px solid #cccccc; text-align: center; line-height: 2rem;}
            table{border-collapse: collapse; margin:20px auto; width:500px; padding:10px }
            table caption{font-size: 1.5rem;}
            table tr:first-child{ background-color: #00BFFF}
        </style>
    </head>
    <body>
        <table>
            <caption></caption>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>工资</th>
            </tr>';
    
            foreach ($data as $staff) {
                $table .= '<tr>';
                $table .= '<td>'.$staff['id'].'</td>';
                $table .= '<td>'.$staff['name'].'</td>';
                $table .= '<td>'.$staff['age'].'</td>';
                $table .= '<td>'.$staff['salary'].'</td>';
                $table .= '</tr>';
            }
            $table .= '</table></body></html>';
            echo $table;
        }
    }

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

    然后是Controller,对数据及视图进行渲染操作:

    实例

    <?php
    
    
    namespace mvc\controller;
    use mvc\view\View;
    use mvc\model\Model;
    
    //spl_autoload_register(function($classname){
    //    if($classname == 'Model'){
    //        require './class/'.$classname.'.php';
    //    }else if($classname == 'View'){
    //        require './view/'.$classname.'.php';
    //    }
    //});
    
    class Controller
    {
        public function index()
        {
            require './model/Model.php';
            $model = new Model('mysql:host=127.0.0.1;dbname=php','root','root');
            $model->select('staff', 10);
            $result = $model->result;
    
            require './view/View.php';
            $view = new View($result);
            $data = $view->getData();
            $view->display($data);
        }
    }

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

    最后需要创建一个入口文件(index.php),即调用Controller中方法:

    实例

    <?php
    /**
     * 入口文件
     */
    
    require './controller/Controller.php';
    use mvc\controller\Controller;
    $controller = new Controller;
    $controller->index();

    运行实例 »

    点击 "运行实例" 按钮查看在线实例

    得出效果图:

    1.png



批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学