Tp5自定义命令行

Tp5自定义命令行


ThinkPHP5.1支持Console应用,通过命令行的方式执行一些URL访问不方便或者安全性较高的操作。

  1. 首先,application下创建console\command\Hello.php
    在这里插入图片描述
  2. 然后在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);
   }
}
  1. 在application\command.php中配置hello命令
<?php
return [
   'app\console\command\Hello'	//注意大小写
];
  1. 最后就是测试命令
  • 先看一下命令有没有定义成功
    在项目的根目录下执行如下命令
php think	

在这里插入图片描述

  • 执行hello命令
    在这里插入图片描述
    *注意属性和选项的写法

发表自己的愚见,有什么不对的地方请大牛指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值