ThinkPHP3自动加载公共函数文件

7d 根目录
├─Application 应用目录
│ ├─Common 公共模块
│ │ ├─Common 公共函数文件目录
│ │ │ ├─index.html
│ │ ├─Config 配置文件目录
│ │ │ ├─config.php
│ │ │ ├─index.html
│ ├─Home Home模块
│ ├─Runtime 运行时的目录
├─Public 资源文件目录
├─ThinkPHP 框架目录
└─index.php 入口文件

1. 默认公共函数文件

在ThinkPHP3.2.3中,默认的公共函数文件位于公共模块./Application/Common下,访问所有的模块之前都会首先加载公共模块下面的配置文件(Conf/config.php)和公共函数文件(Common/function.php),即默认的公共函数文件为./Application/Common/Common/function.php。

不过第一次访问入口文件生成的目录结构中,并没有生成公共函数文件(Common/function.php)。因此,需要自己手动创建./Application/Common/Common/function.php这个文件。

示例:

在./Application/Common/Common下新建function.php:

<?php
// 获取毫秒级时间戳
function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float)sprintf('%.0f', (floatval($t1)+floatval($t2))*1000);
}

?>

在控制器中直接调用即可:

<?php
namespace AdminController;
use ThinkController;
class IndexController extends CommonController {
    public index() {
        $msectime = getMillisecond();   // 不要写成$this->getMillisecond();
        echo json_encode(array(
            'msectime' => $msectime
        ));
    }
}

2. 自定义公共函数文件

在配置文件./Application/Common/Conf/config.php中加入配置:

'LOAD_EXT_FILE' => 'ifunction',

此时就可以自动加载ifunction.php 文件了。
如果有多个需要自动加载的文件,在配置项的值中以","进行分隔。

原文地址:https://www.cnblogs.com/sunshineliulu/p/6605872.html