symfony/console
github地址:GitHub - symfony/console: Eases the creation of beautiful and testable command line interfaces
文档地址:The Console Component (Symfony 5.4 Docs)
默认命令list,可以用register注册一个command命令,之后可以设置其他内容,或者设置命令类再加到框架中。
#Symfony\Component\Console\Application
public function __construct(string $name = 'UNKNOWN', string $version = 'UNKNOWN'){$this->name = $name;$this->version = $version;$this->terminal = new Terminal();$this->defaultCommand = 'list';if (\defined('SIGINT') && SignalRegistry::isSupported()) {$this->signalRegistry = new SignalRegistry();$this->signalsToDispatchEvent = [\SIGINT, \SIGTERM, \SIGUSR1, \SIGUSR2];}}
public function register(string $name){return $this->add(new Command($name));}
public function add(Command $command){……$this->commands[$command->getName()] = $command;……}#Symfony\Component\Console\Command\Command
//设置执行代码
public function setCode(callable $code){if ($code instanceof \Closure) {$r = new \ReflectionFunction($code);if (null === $r->getClosureThis()) {set_error_handler(static function () {});try {if ($c = \Closure::bind($code, $this)) {$code = $c;}} finally {restore_error_handler();}}}$this->code = $code;return $this;}
//设置命令名
public function setName(string $name){$this->validateName($name);$this->name = $name;return $this;}
//设置别名public function setAliases(iterable $aliases){$list = [];foreach ($aliases as $alias) {$this->validateName($alias);$list[] = $alias;}$this->aliases = \is_array($aliases) ? $aliases : $list;return $this;}
//设置帮助内容
public function setHelp(string $help){$this->help = $help;return $this;}
//设置是否隐藏
public function setHidden(bool $hidden /* = true */){$this->hidden = $hidden;return $this;}
//设置描述
public function setDescription(string $description){$this->description = $description;return $this;}
#运行文件
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/Test1Command.php';use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;$application = new Application();
$application->register('test')->addArgument('username', InputArgument::REQUIRED, '用户名')->addOption('pwd', "P", InputArgument::REQUIRED, '密码')->setDescription("test command")->setCode(function (InputInterface $input, OutputInterface $output) {return Command::SUCCESS;});
$test1command = new Test1Command();
$application->add($test1command);
$application->run();#Test1Command
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;class Test1Command extends Command
{protected function configure(){$this->setName("test1");$this->setHelp('This command allows you to create a user...');$this->addArgument('test', InputArgument::REQUIRED, 'test');$this->setDescription("test1 command");}protected function execute(InputInterface $input, OutputInterface $output): int{var_dump($input->getArguments());//$listcommand = $this->getApplication()->get('list');//$listcommand->run($input, $output);$input = new ArrayInput(['command' => 'list']);$listcommand = $this->getApplication()->get('list');$listcommand->run($input, $output);$output->writeln(['Test1 Command','============','',]);return Command::SUCCESS;}
}
InputInterface实体类为Symfony\Component\Console\Input\ArgvInput,该类继承Symfony\Component\Console\Input\Input,会校验参数和用于获取参数。
#Symfony\Component\Console\Application
public function run(InputInterface $input = null, OutputInterface $output = null){if (\function_exists('putenv')) {@putenv('LINES=' . $this->terminal->getHeight());@putenv('COLUMNS=' . $this->terminal->getWidth());}if (null === $input) {//默认input$input = new ArgvInput();}if (null === $output) {//默认输出$output = new ConsoleOutput();}……$exitCode = $this->doRun($input, $output);……}
public function doRun(InputInterface $input, OutputInterface $output){$input->bind($this->getDefinition());……$name = $this->getCommandName($input);……if (!$name) {$name = $this->defaultCommand;$definition = $this->getDefinition();$definition->setArguments(array_merge($definition->getArguments(),['command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),]));}……try {$this->runningCommand = null;// the command name MUST be the first element of the input$command = $this->find($name);} catch (\Throwable $e) {……$alternatives = $e->getAlternatives();……$alternative = $alternatives[0];……$command = $this->find($alternative);}if ($command instanceof LazyCommand) {$command = $command->getCommand();}$this->runningCommand = $command;$exitCode = $this->doRunCommand($command, $input, $output);$this->runningCommand = null;return $exitCode;}#Symfony\Component\Console\Exception\CommandNotFoundException
class CommandNotFoundException extends \InvalidArgumentException implements ExceptionInterface
{private $alternatives;/*** @param string $message Exception message to throw* @param string[] $alternatives List of similar defined names* @param int $code Exception code* @param \Throwable|null $previous Previous exception used for the exception chaining*/public function __construct(string $message, array $alternatives = [], int $code = 0, \Throwable $previous = null){parent::__construct($message, $code, $previous);$this->alternatives = $alternatives;}/*** @return string[]*/public function getAlternatives(){return $this->alternatives;}
}#Symfony\Component\Console\Input\Input
public function __construct(InputDefinition $definition = null){if (null === $definition) {$this->definition = new InputDefinition();} else {//校验选项$this->bind($definition);//校验参数$this->validate();}}
//校验参数
public function validate(){$definition = $this->definition;$givenArguments = $this->arguments;$missingArguments = array_filter(array_keys($definition->getArguments()), function ($argument) use ($definition, $givenArguments) {return !\array_key_exists($argument, $givenArguments) && $definition->getArgument($argument)->isRequired();});if (\count($missingArguments) > 0) {throw new RuntimeException(sprintf('Not enough arguments (missing: "%s").', implode(', ', $missingArguments)));}}
//获取所有参数
public function getArguments(){return array_merge($this->definition->getArgumentDefaults(), $this->arguments);}
//根据变量名获取参数
public function getArgument(string $name){if (!$this->definition->hasArgument($name)) {throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));}return $this->arguments[$name] ?? $this->definition->getArgument($name)->getDefault();}
//设置参数值public function setArgument(string $name, $value){if (!$this->definition->hasArgument($name)) {throw new InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));}$this->arguments[$name] = $value;}
//判断是否有参数
public function hasArgument(string $name){return $this->definition->hasArgument($name);}
//获取全部选项public function getOptions(){return array_merge($this->definition->getOptionDefaults(), $this->options);}
//根据名称获取选项值
public function getOption(string $name){if ($this->definition->hasNegation($name)) {if (null === $value = $this->getOption($this->definition->negationToName($name))) {return $value;}return !$value;}if (!$this->definition->hasOption($name)) {throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));}return \array_key_exists($name, $this->options) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();}
//设置选项值
public function setOption(string $name, $value){if ($this->definition->hasNegation($name)) {$this->options[$this->definition->negationToName($name)] = !$value;return;} elseif (!$this->definition->hasOption($name)) {throw new InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));}$this->options[$name] = $value;}
//判断是否有选项值
public function hasOption(string $name){return $this->definition->hasOption($name) || $this->definition->hasNegation($name);}#Symfony\Component\Console\Input\ArgvInput
protected function parse(){$parseOptions = true;$this->parsed = $this->tokens;while (null !== $token = array_shift($this->parsed)) {$parseOptions = $this->parseToken($token, $parseOptions);}}
protected function parseToken(string $token, bool $parseOptions): bool{if ($parseOptions && '' == $token) {$this->parseArgument($token);} elseif ($parseOptions && '--' == $token) {return false;} elseif ($parseOptions && str_starts_with($token, '--')) {$this->parseLongOption($token);} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {$this->parseShortOption($token);} else {$this->parseArgument($token);}return $parseOptions;}
private function parseShortOption(string $token){$name = substr($token, 1);if (\strlen($name) > 1) {if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {// an option with a value (with no space)$this->addShortOption($name[0], substr($name, 1));} else {$this->parseShortOptionSet($name);}} else {$this->addShortOption($name, null);}}private function addShortOption(string $shortcut, $value){if (!$this->definition->hasShortcut($shortcut)) {throw new RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));}$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);}
运行
php test.php test 123
php test.php test --helpDescription:test commandUsage:test [options] [--] <username>Arguments:username 用户名Options:-P, --pwd 密码-h, --help Display help for the given command. When no command is given display help for the list command-q, --quiet Do not output any message-V, --version Display this application version--ansi|--no-ansi Force (or disable --no-ansi) 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 debugHelp:123
php test.php test1 --helpDescription:test1 commandUsage:test1 <test>Arguments:test testOptions:-h, --help Display help for the given command. When no command is given display help for the list command-q, --quiet Do not output any message-V, --version Display this application version--ansi|--no-ansi Force (or disable --no-ansi) 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 debugHelp:This command allows you to create a user...
php test.php test1 111array(2) {'command' =>string(5) "test1"'test' =>string(3) "111"
}
Console ToolUsage:command [options] [arguments]Options:-h, --help Display help for the given command. When no command is given display help for the list command-q, --quiet Do not output any message-V, --version Display this application version--ansi|--no-ansi Force (or disable --no-ansi) 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 debugAvailable commands:completion Dump the shell completion scripthelp Display help for a commandlist List commandstest test commandtest1 test1 command
Test1 Command
============
相关文章:
symfony/console
github地址:GitHub - symfony/console: Eases the creation of beautiful and testable command line interfaces 文档地址:The Console Component (Symfony 5.4 Docs) 默认命令list,可以用register注册一个command命令,之后可以…...
OSI模型简介及socket,tcp,http三者之间的区别和原理
1.OSI模型简介(七层网络模型) OSI 模型(Open System Interconnection model):一个由国际标准化组织提出的概念模型,试图提供一个使各种不同的计算机和网络在世界范围内实现互联的标准框架。 它将计算机网络体系结构划分为七层,每…...
【leetcode】leetcode69 x的平方根
文章目录 给你一个非负整数 x ,计算并返回 x 的 算术平方根 。原理牛顿法(数值分析中使用到的):二分法 解决方案java 实现实例执行结果 python 实现实例 给你一个非负整数 x ,计算并返回 x 的 算术平方根 。 由于返回类型是整数&…...
springboot与rabbitmq的整合【演示5种基本交换机】
前言: 👏作者简介:我是笑霸final,一名热爱技术的在校学生。 📝个人主页:个人主页1 || 笑霸final的主页2 📕系列专栏:后端专栏 📧如果文章知识点有错误的地方,…...
【设计模式】设计原则-单一职责原则
单一职责原则 类的设计原则之单一职责原则,是最常用的类的设计的原则之一。 百度百科:就一个类而言,应该仅有一个引起它变化的原因。应该只有一个职责。 通俗的讲就是:一个类只做一件事 这个解释更通俗易懂,也更符…...
【C++】-多态的底层原理
💖作者:小树苗渴望变成参天大树🎈 🎉作者宣言:认真写好每一篇博客💤 🎊作者gitee:gitee✨ 💞作者专栏:C语言,数据结构初阶,Linux,C 动态规划算法🎄 如 果 你 …...
【部署】让你的电脑多出一个磁盘来用!使用SSHFS将远程服务器目录挂载到Windows本地,挂载并共享服务器资源
让你的电脑多出一个磁盘来用!---使用SSHFS将远程服务器目录挂载到Windows本地 1. 方法原理介绍2.SSHFS-Win使用教程—实现远程服务器磁盘挂载本地 由于日常主要用 Windows 系统,每次都得 ssh 到服务器上进行取资源(本地磁盘不富裕)…...
/var/lock/subsys目录的作用
总的来说,系统关闭的过程(发出关闭信号,调用服务自身的进程)中会检查/var/lock/subsys下的文件,逐一关闭每个服务,如果某一运行的服务在/var/lock/subsys下没有相应的选项。在系统关闭的时候,会…...
DETR (DEtection TRansformer)基于自建数据集开发构建目标检测模型超详细教程
目标检测系列的算法模型可以说是五花八门,不同的系列有不同的理论依据,DETR的亮点在于它是完全端到端的第一个目标检测模型,DETR(Detection Transformer)是一种基于Transformer的目标检测模型,由Facebook A…...
C++初阶 - 5.C/C++内存管理
目录 1.C/C的内存分布 2.C语言中动态内存管理方式:malloc、calloc、realloc、free 3.C内存管理方式 3.1 new/delete操作内置类型 3.2 new 和 delete操作自定义类型 4.operator new 与 operator delete 函数(重要点) 4.1 operator new 与…...
数学建模学习(3):综合评价类问题整体解析及分析步骤
一、评价类算法的简介 对物体进行评价,用具体的分值评价它们的优劣 选这两人其中之一当男朋友,你会选谁? 不同维度的权重会产生不同的结果 所以找到每个维度的权重是最核心的问题 0.25 二、评价前的数据处理 供应商ID 可靠性 指标2 指…...
【后端面经】微服务构架 (1-5) | 限流:濒临奔溃?限流守护者拯救系统于水火之中!
文章目录 一、前置知识1、什么是限流?2、限流算法A) 静态算法a) 漏桶b) 令牌桶c) 固定窗口d) 滑动窗口B) 动态算法3、限流的模式4、 限流对象4、限流后应该怎么做?二、面试环节1、面试准备2、基本思路3、亮点展现A) 突发流量(针对请求个数而言)B) 请求大小(针对请求大小而言)…...
HDFS异构存储详解
异构存储 HDFS异构存储类型什么是异构存储异构存储类型如何让HDFS知道集群中的数据存储目录是那种类型存储介质 块存储选择策略选择策略说明选择策略的命令 案例:冷热温数据异构存储对应步骤 HDFS内存存储策略支持-- LAZY PERSIST介绍执行使用 HDFS异构存储类型 冷…...
《面试1v1》Kafka消息是采用Pull还是Push模式
🍅 作者简介:王哥,CSDN2022博客总榜Top100🏆、博客专家💪 🍅 技术交流:定期更新Java硬核干货,不定期送书活动 🍅 王哥多年工作总结:Java学习路线总结…...
Windows环境Docker安装
目录 安装Docker Desktop的步骤 Docker Desktop 更新WSL WSL 的手动安装步骤 Windows PowerShell 拉取(Pull)镜像 查看已下载的镜像 输出"Hello Docker!" Docker Desktop是Docker官方提供的用于Windows的图形化桌面应用程序,…...
Spring 6.0官方文档示例(23): singleton类型的bean和prototype类型的bean协同工作的方法(二)
使用lookup-method: 一、实体类: package cn.edu.tju.domain2;import java.time.LocalDateTime; import java.util.Map;public class Command {private Map<String, Object> state;public Map<String, Object> getState() {return state;}public void …...
Docker Compose 容器编排
Docker compose Docker compose 实现单机容器集群编排管理(使用一个模板文件定义多个应用容器的启动参数和依赖关系,并使用docker compose来根据这个模板文件的配置来启动容器) 通俗来说就是把之前的多条docker run启动容器命令 转换为docker…...
while循环
while循环是一种常见的循环结构,它会重复执行一段代码,直到指定的条件不再满足。 基本语法如下: while 条件: # 循环体代码 其中,条件是一个布尔表达式,如果为True,则执行循环体中的代码;如果…...
从JVM指令看String对象的比较
在翻看各类 java 知识中,总会提到如下知识:比较 String 对象,例如: String a1new String("10"); String a2"10"; String a3"1""0";//结果 System.out.println(a1a2); //false System.ou…...
python与深度学习(六):CNN和手写数字识别二
目录 1. 说明2. 手写数字识别的CNN模型测试2.1 导入相关库2.2 加载数据和模型2.3 设置保存图片的路径2.4 加载图片2.5 图片预处理2.6 对图片进行预测2.7 显示图片 3. 完整代码和显示结果4. 多张图片进行测试的完整代码以及结果 1. 说明 本篇文章是对上篇文章训练的模型进行测试…...
Multisim仿真进阶指南:从零构建PWM调光电路(附波形分析与调试秘籍)
1. PWM调光电路:从原理到Multisim实现 第一次接触PWM调光电路时,我被它精准的亮度控制能力惊艳到了。相比简单的呼吸灯电路,PWM调光可以通过调节占空比来实现LED从完全熄灭到最大亮度的无级调节,这在实际项目中特别实用。比如智能…...
3步搞定Mac NTFS读写:开源工具Nigate让跨平台文件传输无忧
3步搞定Mac NTFS读写:开源工具Nigate让跨平台文件传输无忧 【免费下载链接】Free-NTFS-for-Mac Nigate: An open-source NTFS utility for Mac. It supports all Mac models (Intel and Apple Silicon), providing full read-write access, mounting, and managemen…...
基于Dify工作流的多阶段检索与筛选系统
Dify工作流中实现查询优化(QO):将查询复杂度分类法与QOL框架融入工作流 假设用户输入的问题是:“请帮我整理2026年1月1日至今在GitHub上发布的金融商业行业开源项目” 为了整理2026年1月1日至今在GitHub上发布的金融商业行业开源…...
gallery性能分析工具:找出本地AI平台的性能瓶颈
gallery性能分析工具:找出本地AI平台的性能瓶颈 【免费下载链接】gallery A gallery that showcases on-device ML/GenAI use cases and allows people to try and use models locally. 项目地址: https://gitcode.com/GitHub_Trending/gallery44/gallery 在…...
Flutter地图集成与跨平台定位从0到1:3大平台配置+5个避坑指南
Flutter地图集成与跨平台定位从0到1:3大平台配置5个避坑指南 【免费下载链接】flutter_amap A Flutter plugin use amap.高德地图flutter组件 项目地址: https://gitcode.com/gh_mirrors/fl/flutter_amap 在移动应用开发中,地图集成和定位服务是许…...
SEO接单平台怎么选
SEO接单平台怎么选?详细指南解析 在当今数字化时代,SEO接单平台已经成为许多企业和自由职业者获取客户资源的重要途径。市场上充斥着各种SEO接单平台,如何选择一个合适的平台对于提升工作效率和业务发展至关重要。本文将详细介绍如何选择SEO…...
如何高效管理ExHentai漫画收藏:终极标签化管理解决方案
如何高效管理ExHentai漫画收藏:终极标签化管理解决方案 【免费下载链接】exhentai-manga-manager ExHentai本地漫画标签管理阅读应用, ExHentai local manga tag-manager and reader 项目地址: https://gitcode.com/gh_mirrors/ex/exhentai-manga-manager 你…...
B站硬核会员智能答题:AI驱动的高效通关解决方案
B站硬核会员智能答题:AI驱动的高效通关解决方案 【免费下载链接】bili-hardcore bilibili 硬核会员 AI 自动答题脚本,直接调用 B 站 API,非 OCR 实现 项目地址: https://gitcode.com/gh_mirrors/bi/bili-hardcore B站硬核会员身份象征…...
C++11三大核心特性深度解析:类型特征、时间库与原子操作
C11三大核心特性深度解析:类型特征、时间库与原子操作 引言 C11标准的发布标志着C语言进入了现代编程的新纪元。在众多令人瞩目的新特性中,类型特征(<type_traits>)、时间库()和原子操作࿰…...
打造你的专属数字伙伴:BongoCat虚拟桌宠完全指南 [特殊字符]
打造你的专属数字伙伴:BongoCat虚拟桌宠完全指南 🐱 【免费下载链接】BongoCat 🐱 跨平台互动桌宠 BongoCat,为桌面增添乐趣! 项目地址: https://gitcode.com/gh_mirrors/bong/BongoCat 你是否曾幻想过在单调的…...
