现在我们要加入一些配置文件
首先在lib目录下建一个config.php 并且加入俩个方法 get() 加载一个配置文件 all()加载多个配置文件
<?php namespace core\lib; class config { static public $conf = array(); //加载配置文件 static public function get($name,$file) { if(isset(self::$conf[$file])) { return self::$conf[$file][$name]; } else { $path = PATH .'/core/config/'.$file.'.php';//配置文件路径 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); } } } static public function all($file) { if(isset(self::$conf[$file])) { return self::$conf[$file]; } else { $path = PATH .'/core/config/'.$file.'.php';//配置文件路径 if(is_file($path)) { $conf = include $path; self::$conf[$file] = $conf; return $conf; }else { throw new \Exception('找不到配置文件'.$file); } } } }然后在core目录下建一个文件夹叫config用来存放配置文件
首先我们见一个路由的配置文件 route.php
然后我们打开lib下的route.php<?php return array( 'CONTROLLER' => 'index',//默认控制器 'ACTION' => 'index'//默认方法 );
把index修改一下
<?php namespace core\lib; class route { public $ctrl; public $action; public function __construct() { /** * 1、获取URL中参数 * 2、返回对应控制器和方法 */ $url = $_SERVER['REQUEST_URI']; if(isset($url) && $url != '/') { $path = explode('/',substr($url,strpos($url,'/?c=')+4)); if(isset($path[0])){ $this->ctrl = $path[0]; } if(isset($path[1])){ $this->action = $path[1]; } else { $this->action = config::get('ACTION','route'); } } else { $this->ctrl = config::get('CONTROLLER','route'); $this->action = config::get('ACTION','route'); } } }然后在config目录下建一个database.php
<?php return array( 'DSN' => 'mysql:host=localhost;dbname=laravel5.2', 'USERNAME' => 'root', 'PASSWD' => 'root' );然后到lib目录下的model.php中修改
<?php namespace core\lib; class model extends \PDO { public function __construct() { $database = config::all('database'); try {//如果连接数据库异常,就显示错误信息 parent::__construct($database['DSN'],$database['USERNAME'],$database['PASSWD']); } catch (\PDOException $e) { p($e->getMessage()); } } }这样基本的配置类就做完了