控制台
要使用控制台指令,你必须确保应用根目录下存在think文件(不要随便删除或者改名)。
该文件内容如下,主要是执行一个console应用。
!/usr/bin/env php
<?php
namespace think;
// 加载基础文件
require DIR . '/vendor/autoload.php';
// 应用初始化
(new App())->console->run();
控制台指令的执行格式一般为(在应用根目录下执行):
php think 指令 参数1 参数2 ...
在控制台think入口执行的指令是没有多应用的概念的,你可以把控制台指令理解为单应用模式。控制台需要操作应用的时候,一般由指令自己处理。
快速创建指令
可以用make:command指令快速生成一个应用指令文件
php think make:command Hello
然后在config\console.php中添加指令
return [
'commands' => [
'hello' => app\command\Hello::class,
]
];
然后就可以运行
php think
查看下指令列表中是否有Hello指令
执行指令测试
php think hello
指定指令名称
创建指令的时候可以支持第二个可选参数用于指定指令名称。默认情况下,指令名称就是指令文件名的小写,也就是说上面的指令等同于
php think make:command Hello hello
如果你需要指定不同与默认规则的指令名称,可以使用
php think make:command HelloWorld hello_world
指令名称建议使用小写加下划线规范。
然后在config\console.php中添加指令
return [
'commands' => [
'hello_world' => app\command\HelloWorld::class,
]
];
现在,可以使用下面的指令测试
php think hello_world
创建不同命名空间的指令
默认情况下,创建的指令的命名空间都是 app\command开头的,如果你需要指定命名空间的话,可以通过使用完整的指令类名来生成指令。
php think make:command app\command\test\Hello
然后在config\console.php中添加指令
return [
'commands' => [
'hello' => app\command\test\Hello::class,
]
];
指令测试
php think hello
创建分组指令
如果你需要创建一组指令,比如hello:a以及 hello:b两条指令,可以使用
php think make:command hello/A hello:a
php think make:command hello/B hello:b
然后在config\console.php中添加指令
return [
'commands' => [
'hello:a' => app\command\hello\A::class,
'hello:b' => app\command\hello\B::class,
]
];
运行指令测试。
php think hello:a
hello:a
php think hello:b
hello:b
在扩展中注册指令
框架内置了一些基本的指令,你也可以通过扩展的方式注册额外的指令。要在你的扩展中注册指令,首先必须确保在你的composer.json文件中的extra配置项中添加如下类似代码(这里以官方的think-multi-app扩展为例):
"extra": {
"think":{
"services":[
"think\app\Service"
]
}
},
在你的扩展里面定义一个Service类(必须继承think\Service类),然后在register方法中注册你的指令。
namespace think\app;
use think\Service as BaseService;
class Service extends BaseService
{
public function register()
{
$this->commands([
'build' => command\Build::class,
]);
}
}
这里额外注册了一个build指令,所以,我们就可以在安装完扩展后执行
php think build
发表评论