创建项目文件夹:
cd ~/work/php/
mkdir -pv app-cmd && cd app-cmd
安装Console组件:
composer require symfony/console
创建自己的代码目录:
mkdir -p src/Command # 创建自己的代码目录
注册命名空间:
编辑 composer.json
文件如下,然后在命令行输入composer dump-autoload
:
{
"require": {
"symfony/console": "^4.3"
},
"autoload": {
"psr-4":{
"App\\": "src/"
}
}
}
创建命令文件:
在 src/Command
路径下创建 CreateUserCommand.php
文件,并写入:
<?php
/**
* Created by PhpStorm.
* User: jinchunguang
* Date: 19-11-20
* Time: 下午1:57
*/
// src/Command/CreateUserCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CreateUserCommand extends Command
{
/**
* 命令的名称
* @var string
*/
protected static $defaultName = 'app:create-user';
/**
* 配置命令
*/
protected function configure()
{
$this
// 运行“php artisan list”时显示的简短描述
->setDescription('Creates a new user.')
// 运行命令时显示的完整命令说明,`php artisan app:create-user --help`时候会显示
->setHelp('This command allows you to create a user...');
}
/**
* 执行任务
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
/**
* 在每行末尾添加“\n”
*/
// 将多行输出到控制台
$output->writeln([
'User Creator',
'============',
'',
]);
// 将单号行输出到控制台
$output->writeln('Whoa!');
/**
* 在每行末尾不添加“\n”
*/
// 将多行输出到控制台(在每行末尾不添加“\n”)
$output->write([
'姓名:',
'kim',
'年龄:',
'25',
]);
// 将单号行输出到控制台(在每行末尾不添加“\n”)
$output->write(PHP_EOL . 'create a user.');
}
}
6.在项目根目录下,创建Console组件的入口文件 artisan
并写入:
#!/usr/bin/env php
<?php
// application.php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Console\Application;
$application = new Application();
// ... register commands
$application->add(new \App\Command\CreateUserCommand());
$application->run();
使用组件:
➜ app-cmd php artisan
Console Tool
Usage:
command [options] [arguments]
Options:
-h, --help Display this help message
-q, --quiet Do not output any message
-V, --version Display this application version
--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:
help Displays help for a command
list Lists commands
app
app:create-user
此时就可以看到我们自定义的app:create-user
命令了
执行自定义命令

7如果要获取输入参数
<?php
/**
* Created by PhpStorm.
* User: jinchunguang
* Date: 19-11-20
* Time: 下午1:57
*/
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class UpdateUserCommand extends Command
{
/**
* 命令的名称
* @var string
*/
protected static $defaultName = 'app:update-user';
/**
* 配置命令
*/
protected function configure()
{
$this
->setDescription('Update a new user.')
->setHelp('This command allows you to update a user...')
// 配置参数
->addArgument('username', InputArgument::REQUIRED, 'The username of the user.');
}
/**
* 执行任务
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
//-----------------------------------------------
// 控制台输入
//-----------------------------------------------
$output->writeln([
'User Creator',
'============',
'',
]);
// 使用getArgument()来获取参数值参数值
$output->writeln('Username: '.$input->getArgument('username'));
}
}

8 命令生命周期
- initialize() (可选的)
该方法在interact()和execute() 方法之前执行。其主要目的是初始化其余命令方法中使用的变量。 - interact() (可选的)
此方法在之后initialize()和之前执行execute()。其目的是检查某些选项/参数是否丢失,并以交互方式向用户询问这些值。这是您最后一个缺少选项/参数的地方。执行此命令后,缺少选项/参数将导致错误。 - execute() (需要)
此方法在interact()和之后执行initialize()。它包含您要命令执行的逻辑。
<?php
/**
* Created by PhpStorm.
* User: jinchunguang
* Date: 19-11-20
* Time: 下午1:57
*/
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class QueryUserCommand extends Command
{
/**
* 命令的名称
* @var string
*/
protected static $defaultName = 'app:query-user';
/**
* 配置命令
*/
protected function configure()
{
$this
->setDescription('Query a new user.')
->setHelp('This command allows you to query a user...');
}
/**
* 该方法在interact()和execute() 方法之前执行
* 初始化其余命令方法中使用的变量
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function initialize(InputInterface $input, OutputInterface $output)
{
$output->writeln(__METHOD__ . "\t" . '初始化工作');
}
/**
* 此方法在之后initialize()和之前执行execute()
* 检查某些选项/参数是否丢失,并以交互方式向用户询问。执行此命令后,缺少选项/参数将导致错误。
* @param InputInterface $input
* @param OutputInterface $output
*/
protected function interact(InputInterface $input, OutputInterface $output)
{
$output->writeln(__METHOD__ . "\t" . '检查某些选项/参数是否丢失');
}
/**
* 此方法在interact()和之后执行initialize()
* 执行的逻辑。
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln(__METHOD__ . "\t" . '执行任务');
}
}

9 其他功能
控制台输出着色和样式
// green text
$output->writeln('<info>foo</info>');
// yellow text
$output->writeln('<comment>foo</comment>');
// black text on a cyan background
$output->writeln('<question>foo</question>');
// white text on a red background
$output->writeln('<error>foo</error>');
// green text
$output->writeln('<fg=green>foo</>');
// black text on a cyan background
$output->writeln('<fg=black;bg=cyan>foo</>');
// bold text on a yellow background
$output->writeln('<bg=yellow;options=bold>foo</>');
// bold text with underscore
$output->writeln('<options=bold,underscore>foo</>');
控制台隐藏
$this
->setHidden(true)// 命令在控制台隐藏,实际上是可以执行的
->setDescription('Delete a new user.')
->setHelp('This command allows you to delete a user...');

进度条
<?php
/**
* Created by PhpStorm.
* User: jinchunguang
* Date: 19-11-20
* Time: 下午1:57
*/
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
class RepairUserCommand extends Command
{
/**
* 命令的名称
* @var string
*/
protected static $defaultName = 'app:repair-user';
/**
* 配置命令
*/
protected function configure()
{
$this
->setDescription('Repair a new user.')
->setHelp('This command allows you to repair a user...');
}
/**
* 执行的逻辑
* @param InputInterface $input
* @param OutputInterface $output
* @return int|null|void
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$io = new SymfonyStyle($input, $output);
$len = 1000;
// 获取参数,控制台不可见
$pwd=$io->askHidden('请输入口令?', function ($password) {
if (empty($password)) {
throw new \RuntimeException('口令不能为空.');
}
return $password;
});
// 错误输出
$confirm = $io->confirm('请再次确认你输入的口令为:'.$pwd,false);
if(!$confirm){
// 显示错误
$io->getErrorStyle()->warning('操作取消');
}
// 第二个参数为默认值
$len=$io->ask('请输入进度条长度?',$len);
// 命令的标题
$io->title('进度条测试');
$io->progressStart($len);
for ($i = 0; $i <= $len; $i++) {
usleep(100*1000);
$io->progressAdvance(1);
}
$io->progressFinish();
}
}

网友评论