AI编程生活评测

ThinkPHP 5.1自动生成模块及目录、文件

编程笔记 / 2018-06-03 / 2 min

试用一下 ThinkPHP 5.1 这最新版的 TP 框架,创建项目很简单,在 web 根目录使用 composer 搞定:

composer create-project topthink/think tp5 5.1.* --prefer-dist

这里面的 tp5 是新建项目的文件夹名了, 5.1.* 代表指定版本为 >=5.1, <5.2 的版本。

项目创建好了,然后我们就需要创建模块

ThinkPHP 5.1 提供了自动生成模块的途径让这个工作更快更酷。

第一步:编辑 build.php 文件

编辑项目根目录也就是上文 tp5 目录下的 build.php 文件。 比如这样:

return [
    // 生成应用公共文件
    &#039;__file__&#039; =&gt; [&#039;common.php&#039;],

    // 定义demo模块的自动生成 (按照实际定义的文件名生成)
    &#039;demo&#039;     =&gt; [
        &#039;__file__&#039;   =&gt; [&#039;common.php&#039;],
        &#039;__dir__&#039;    =&gt; [&#039;behavior&#039;, &#039;controller&#039;, &#039;model&#039;, &#039;view&#039;],
        &#039;controller&#039; =&gt; [&#039;Index&#039;, &#039;Test&#039;, &#039;UserType&#039;],
        &#039;model&#039;      =&gt; [&#039;User&#039;, &#039;UserType&#039;],
        &#039;view&#039;       =&gt; [&#039;index/index&#039;],
    ],

    &#039;socketio&#039;     =&gt; [
        &#039;__file__&#039;   =&gt; [&#039;common.php&#039;],
        &#039;__dir__&#039;    =&gt; [&#039;controller&#039;, &#039;model&#039;, &#039;view&#039;],
        &#039;controller&#039; =&gt; [&#039;Index&#039;, &#039;Server&#039;],
        &#039;model&#039;      =&gt; [],
        &#039;view&#039;       =&gt; [&#039;index/index&#039;],
    ],
    // 其他更多的模块定义
];

其中:

__dir__ 表示生成目录(支持多级目录)
__file__ 表示生成文件(不定义默认会生成 config.php 文件)
controller 表示生成controller类
model表示生成model类
view表示生成html文件(支持子目录)

第二步:将 build.php 复制到应用的根目录下(默认是 /Application 目录)。

复制过来之后是这样的目录结构: ThinkPHP 5.1 自动生成模块

第三步:在项目根目录下运行命令:

php think build
// 生成成功输出
Successed 

去应用目录下看,按上面的 build.php 生成模块后的目录结构: ThinkPHP5.1自动生成模块

参考文档:

官方文档传送门