tp5命令行基础介绍

    • 查看指令
    • 生成模块
    • 生成文件
    • 生成类库映射文件
    • 生成路由缓存文件
    • 生成数据表字段缓存文件
    • 指令扩展示例
    • 命令行调试
    • 命令行颜色支持
    • 调用命令

查看指令

命令行工具需要在命令行下面执行,请先确保你的php.exe已经加入了系统环境变量Path

应用的命令行入口文件是应用根目录的think文件,其内容如下:

// 定义项目路径
define('APP_PATH', './application/');

// 加载框架命令行引导文件
require './thinkphp/console.php';

你也可以自定义think文件,更改应用目录。

要执行命令,首先进入命令行,并切换当前目录到应用的根目录(也就是think文件所在目录)下面,执行:

php think

会显示当前支持的所有指令:

>php think
Think Console version 0.1

Usage:
  command [options] [arguments]

Options:
  -h, --help            Display this help message
  -V, --version         Display this console version
  -q, --quiet           Do not output any message
      --ansi            Force ANSI output
      --no-ansi         Disable ANSI output
  -n, --no-interaction  Do not ask any interactive question
  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Available commands:
  build              Build Application Dirs
  help               Displays help for a command
  list               Lists commands
 make
  make:controller    Create a new controller class
  make:model         Create a new model class
 optimize
  optimize:autoload  Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.
注意

在win10的周年版中运行会出现乱码,请使用PowerShell运行。

使用

>php think list 

可以获得相同的结果。

如果输入一个不存在的指令,系统会自动搜索相关的指令并提示,例如:

>php think make

会显示

生成模块

下面我们给应用生成一个新的模块test,首先需要在application目录下面创建一个build.php定义文件,文件内容如下:

return [
    // 定义test模块的自动生成
    'test' => [
        '__dir__'    => ['controller', 'model', 'view'],
        'controller' => ['User', 'UserType'],
        'model'      => ['User', 'UserType'],
        'view'       => ['index/index', 'index/test'],
    ],
];

然后在命令行下面,执行:

>php think build
Successed

如果显示Successed则表示生成成功。

注意,命令行指令是区分大小写的,所以如果执行

>php think Build

会报错。

我们可以看到application目录下面已经生成了一个test模块目录,包括下面的子目录及文件:

test
├─controller
│    ├─Index.php
│    ├─User.php
│    └─UserType.php
├─model
│    ├─User.php
│    └─UserType.php
├─view
│    └─index
│      ├─index.html
│      └─test.html
├─common.php
└─config.php

接下来,我们可以访问

http://tp5.com/test/

会显示:

image

我们在build.php文件中并没有定义Index控制器,但仍然生成了一个默认的Index控制器文件以及欢迎页面,这是为了避免模块访问出错。

生成文件

还可以用make指令单独生成某个应用类库文件,例如:

php think make:controller test/Blog

会自动为test模块生成一个 Blog控制器文件。

注意,默认生成的控制器类是属于资源控制器,并且继承了 hinkController。

如果希望生成一个空的控制器,可以使用

php think make:controller test/Blog --plain

又或者生成一个模型文件

php think make:model test/Blog

生成类库映射文件

在生成类库文件之后,我们强烈建议使用命令行生成类库映射文件,可以提高自动加载的性能,用法如下:

>php think optimize:autoload

执行完毕,会在RUNTIME_PATH目录下面生成一个classmap.php文件,包括了系统和应用的所有类库文件的映射列表。

生成路由缓存文件

如果你的应用定义了大量的路由规则,那么建议在实际部署后生成路由缓存文件,可以免去路由注册的开销,从而改善路由的检测效率,用法如下:

>php think optimize:route

执行完毕,会在RUNTIME_PATH目录下面生成一个route.php文件,包括了应用的所有路由规则定义列表。

注意

路由缓存文件只会缓存在application/route.php文件中配置和动态注册的路由规则,因此请确保你没有在其它的文件中进行路由的注册。

生成数据表字段缓存文件

如果你希望提高查询的性能,可以通过生成字段缓存来减少查询。用法如下:

>php think optimize:schema

执行完毕,会在RUNTIME_PATH目录下面创建schema目录,然后在该目录下面按照database.table.php的文件命名生成数据表字段缓存文件。

也可以指定数据库生成字段缓存(必须有用户权限),例如,下面指定生成demo数据库下面的所有数据表的字段缓存信息。

php think optimize:schema --db demo

还可以读取模块的模型类来生成数据表字段缓存(这个适合多数据库连接的情况),如下:

php think optimize:schema --module index

会读取index模块的模型来生成数据表字段缓存。

注意

如果模型类没有继承thinkModel或者是抽象类的话,不会生成对应模型的字段缓存。

更新数据表字段缓存也是同样的方式,每次执行都会重新生成缓存。如果需要单独更新某个数据表的缓存,可以使用:

php think optimize:schema --table think_user

支持指定数据库名称

php think optimize:schema --table demo.think_user

指令扩展示例

命令行的作用远不止生成文件这么简单,同时应用也可以很方便的扩展自己的指令,我们来扩展一个用于清理缓存目录的指令clear

注意

最新版本已经内置clear指令了,下面的示例可以直接使用内置的clear指令进行学习和测试。

首先,我们创建一个指令类 appconsoleClear,内容如下:

<?php
namespace appconsole;

use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleinputOption;
use thinkconsoleOutput;

class Clear extends Command
{
    protected function configure()
    {
        // 指令配置
        $this
            ->setName('clear')
            ->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to clear', null)
            ->setDescription('Clear runtime file');
    }

    protected function execute(Input $input, Output $output)
    {
        $path  = $input->getOption('path') ?: RUNTIME_PATH;
        $files = scandir($path);
        if ($files) {
            foreach ($files as $file) {
                if ('.' != $file && '..' != $file && is_dir($path . $file)) {
                    array_map('unlink', glob($path . $file . '/*.*'));
                } elseif (is_file($path . $file)) {
                    unlink($path . $file);
                }
            }
        }
        $output->writeln("Clear Successed");
    }
}

一个合法的指令类,没有固定的目录和命名空间要求,但必须继承thinkconsolecommandCommand或者其子类,并且定义configureexecute两个方法。

然后,在application目录下面的command.php(如果不存在则创建)文件中添加如下内容:

return [
    'appconsoleClear',
];

表示给应用增加一个命令行Clear指令,我们可以用list指令来验证是否已经成功注册Clear指令:

>php think list

运行后如果看到

image

表示指令注册成功,接下来可以测试下该指令:

>php think clear
Clear Successed

该指令并不会删除目录,仅仅删除目录下面(包括子目录)的文件。

clear指令还定义了一个--path参数用于指定目录,下面是一个指定目录删除文件的用法,我们仅仅需要删除日志文件:

>php think clear --path d:www	p5
untimelog
Clear Successed

--path参数还有一个简化用法-d

>php think clear -d d:www	p5
untimelog
Clear Successed

命令行调试

命令行一旦执行错误,只能看到简单的错误信息,如果需要调试详细的Trace信息,可以使用 -v 参数来显示,例如:
假设Clear指令文件中使用了一个未定义的变量pathp,那么我们可以使用

>php think clear

会显示如下错误:
image

我们需要查看具体的Trace信息,可以使用

>php think clear -v

会看到类似下面的错误信息:

image

命令行颜色支持

为了让命令行工具更加有趣,think命令行支持颜色输出,并且内置了几种颜色样式,还可以自己自定义颜色样式输出。

windows下面命令行颜色输出支持需要windows 10.0.10580以上版本支持

我们添加一个color指令用于演示颜色输出效果,代码如下:

<?php
namespace appconsole;

use thinkconsolecommandCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
use thinkconsoleoutputformatterStyle;

class Color extends Command
{
    protected function configure()
    {
        $this
            ->setName('color')
            ->setDescription('Show Color text');
    }

    protected function execute(Input $input, Output $output)
    {
        // 输出info样式
        $output->writeln("<info>this is info</info>");
        // 输出error样式
        $output->writeln("<error>this is error</error>");
        // 输出comment样式
        $output->writeln("<comment>this is comment</comment>");
        // 输出question样式
        $output->writeln("<question>this is question</question>");
        // 输出highlight样式
        $output->writeln("<highlight>this is highlight</highlight>");
        // 输出warning样式
        $output->writeln("<warning>this is warning</warning>");
        // 输出混合样式
        $output->writeln("this is <info>info</info>, this is <error>error</error>,this is <comment>comment</comment>,this is <question>question</question>,this is <highlight>highlight</highlight>, this is <warning>warning</warning>");
        // 自定义输出样式
        $output->getFormatter()->setStyle('custom', new Style('black', 'white'));
        $output->writeln("<custom>this is style</custom>");
    }
}

command.php定义修改如下:

return [
    'appconsoleClear',
    'appconsoleColor',
];

然后执行下面的指令:

>php think color

运行后就可以看到:

image

调用命令

在代码里面可以直接调用执行命令行的某个命令,例如:

namespace appindexcontroller;

use thinkConsole;

class Index 
{
    public function index()
    {
        // 调用命令行的指令
        $output = Console::call('make:model',['index/Blog']);
        return $output->fetch();
    }
}

Console::call方法的第一个参数就是指令名称,后面的第二个参数是一个数组,表示调用的参数。
如果我们要创建一个demo模块的话,应该是:

Console::call('build',['--module', 'demo']);

当访问

http://tp5.com 

页面会输出

Model created successfully.

可以在application/index/model/目录下面发现已经生成了一个Blog模型文件。

当我们再次刷新页面的话,会看到页面输出

Model already exists!

表示模型已经创建过了,无需再次创建。

使用Console::call方法调用指令执行不会看到最终的输出结果,需要使用fetch方法获取输出信息,一旦发生错误,则会抛出异常。

原文地址:https://www.cnblogs.com/q1104460935/p/6913319.html