Tp5自定义命令行
ThinkPHP5.1支持Console应用,通过命令行的方式执行一些URL访问不方便或者安全性较高的操作。
- 首先,application下创建console\command\Hello.php
- 然后在Hello.php创建命令
<?php
namespace app\console\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
class Hello extends Command
{
protected function configure()
{
$this->setName('hello') //定义命令名称
->addArgument('name', Argument::REQUIRED, "your name") //定义命令参数(必填)
->addArgument('sex', Argument::OPTIONAL, "your sex") //定义命令参数(非必填)
->addOption('city', null, Option::VALUE_REQUIRED, 'city name') //定义命令选项(非必填)
->setDescription('To introduce myself'); //定义此命令说明
}
protected function execute(Input $input, Output $output)
{
//接收参数
$name = trim($input->getArgument('name'));
$sex = trim($input->getArgument('sex'));
$name = 'My name is '.$name;
$sex = $sex ? PHP_EOL . 'I am a '.$sex : PHP_EOL . 'My sex is a secret';
if ($input->hasOption('city')) { //接收选项
$city = PHP_EOL . 'From ' . $input->getOption('city');
} else {
$city = '';
}
$output->writeln("Hello," . $name . '!' . $sex . '!' . $city);
}
}
- 在application\command.php中配置hello命令
<?php
return [
'app\console\command\Hello' //注意大小写
];
- 最后就是测试命令
- 先看一下命令有没有定义成功
在项目的根目录下执行如下命令
php think
- 执行hello命令
*注意属性和选项的写法
发表自己的愚见,有什么不对的地方请大牛指出!