不知道大家注意了没有,前几篇文章我都没有涉及到配置文件,可是在一个项目中,配置文件又是比不可少的。
现在假设将route.php中的默认控制器和action变为可配置的,怎么弄呢?
我们使用最简单的方式:
1 2 $defaultcontroller = 'index';
3 $defaultaction = 'index';
然后在route.php中include这个文件:
1 2 include app_path . '/config.php';
1 $controller = empty($_get['c']) ? $defaultcontroller : trim($_get['c']); //设置了默认的控制器
2 $action = empty($_get['a']) ? $defaultaction : trim($_get['a']); //设置了默认的action
当然也可以使用这种方式:
1 'index',
4 'defaultaction' => 'index'
5 );
还是在route.php中include:
1 ')) {
08 //一维
09 return isset($_config[$name]) ? $_config[$name] : null;
10 } else {
11 //目前只支持二维
12 $name = explode('=>',$name);
13 returnisset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : null;
14 }
15 } else {
16 if(!strpos($name,'=>')) {
17 //直接设置
18 $_config[$name] = $val;
19 } else {
20 //设置二维
21 $name = explode('=>',$name);
22 $_config[$name[0]][$name[1]] = $val;
23 }
24 }
25 } elseif(is_array($name)) {
26 foreach($name as $key=>$value) {
27 $_config[$key] = $value;
28 }
29 return ;
30 } else {
31 throw new exception('参数类型出错');
32 return ;
33 }
34 }
看着代码挺长的,实际上原理很简单,如果传递的参数只有一个,那么第二个参数就调用默认参数,即null,再识别是否第一个参数是否是字符串,那么这个函数就识别为读取,如果第二个参数不为空或第一个参数为数组,那么就识别为设置!!
由于我自己现在比较懒,而且我用这个函数用的函数蛮顺手的,所以在这儿我就直接用这个函数来作为例子了,更多内容可以查看toper的/library/toper/function.php。
比如现在要读取defaultcontroller,那么只要使用c('defaultcontroller')即可,如果要设置,那么使用c('defaultcontroller','index')!!!
现在我们只需要在入口文件中导入这个function.php即可:
1 2 defined('app_path') define('app_path',dirname(__file__) . '/..');
3 defined('framework_path') define('framework_path',app_path . '/library/test');
4 defined('modules_path') define('modules_path',app_path . '/userapps/modules');
5 include framework_path . '/function.php';
6 include framework_path . '/route.php';
7 route::run();
大家可能注意到了,c函数最开始的时候,里面没有存放任何元素,那么我们怎么样进行初始化,将配置文件的内容写入c函数呢?
之前我们将配置文件存放在项目根目录,这样实际上是不符合之前我们的约定的规范,所以现在讲这个配置文件剪切到/userapps/configs目录下面,为了更方便的使用这个路径,我们定义一个configs_path来指向配置文件的路径。
现在我们看看入口文件变成了什么样了:
1 2 defined('app_path') define('app_path',dirname(__file__) . '/..');
3 defined('framework_path') define('framework_path',app_path . '/library/test');
4 defined('modules_path') define('modules_path',app_path . '/userapps/modules');
5 defined('configs_path') define('configs_path',app_path . '/userapps/configs');
6 include framework_path . '/function.php';
7 c(include configs_path . '/config.php'); //写入配置信息
8 include framework_path . '/route.php';
9 route::run();
然后我们修改一下route.php
01 $action();
15 } else {
16 echo 'the method does not exists';
17 }
18 } else {
19 echo 'the class does not exists';
20 }
21 } else {
22 echo 'controller not exists';
23 }
24 }
25 }
