学习封装mvc框架(七)配置加载类

来源:互联网 发布:sql注入与防御 编辑:程序博客网 时间:2024/05/21 09:28

为了提高我们框架的健壮性,下面我们来写一个配置类来加载我们的配置

首先在core\lib下建立conf.php

<?php  namespace core\lib;class conf{    static public $conf = array();                            //建一个配置属性来存放配置    static public function get($name,$file)                   //get方法加载单个配置文件    {        /**         * 1.判断配置文件是否存在         * 2.判断对应配置是否存在         * 3.配置已经被加载过,缓存一下配置         */        if(isset(self::$conf[$file])){            return self::$conf[$file][$name];                       //判断盖缓存文件是否已经加载配置文件,若缓存过直接返回                                     } else {            // p(1);                                                   //验证是否只加载一次配置文件            $path = MVC.'/core/config/'.$file.'.php';            // p($file);                                            //输出缓存的配置文件名            if(is_file($path)){                $conf = include $path;                if(isset($conf[$name])){                    self::$conf[$file] = $conf;                                     //把配置存入配置属性(静态配置属性)                    return $conf[$name];                                            //返回要加载的配置                } else {                    throw new \Exception('没有这个配置项'.$name);                   //配置项异常                }            } else {                throw new \Exception('找不到配置文件'.$file);                        //没有这个配置文件                                     }        }    }
查看一下core/config/下是否有route.php ,该文件就是生成的项目缓存配置文件
下面我们把数据库配置文件写下:

先更改一下lib下路由类route.php

把原先的

   // $this->ctrl = 'index';   // $this->action = 'index';
替换为

    $this->ctrl = conf::get('CTRL','route');             //因为用的比较多,所以直接引入配置文件    $this->action = conf::get('ACTION','route');
然后在indexCtrl中

      $temp = new \core\lib\model();           print_r($temp);
打印一下:


数据库配置成功!

上面我们写的是get方法来加载单个配置文件,下面我们写一个all方法来加载整个配置文件

  static public function all($file)               {          if(isset(self::$conf[$file])){            return self::$conf[$file];        } else {            //(1);            $path = MVC.'/core/config/'.$file.'.php';            // p($file);            if(is_file($path)){                $conf = include $path;                if(isset($conf)){                self::$conf[$file] = $conf;                return $conf;                } else {                throw new \Exception('没有这个配置项');                }            }else{            throw new \Exception('找不到配置文件'.$file);            }        }    }
好,我们在model类中加载

<?php namespace core\lib;use core\lib\conf;    class model extends \PDO    {         public function __construct()         {              $database = conf::all('database');              调用all方法括号里为所调用的配置文件名称              p($database);             try{                parent::__construct($database['dsn'],$database['username'],$database['password']);             } catch(\PDOException $e) {                 p($e->getMessage());                           //连接不上抛出异常             }         }    }?>
ok,完成了!

0 0
原创粉丝点击