interitty / console
标准 Symfony/Console 扩展,增加了适用于 Interitty 项目的一些特定功能。
Requires
- php: ~8.3
- dg/composer-cleaner: ~2.2
- interitty/utils: ~1.0
- symfony/console: ~7.0
Requires (Dev)
- interitty/code-checker: ~1.0
- interitty/di: ~1.0
- interitty/phpunit: ~1.0
- nette/application: ~3.
- nette/bootstrap: ~3.2
- nette/caching: ~3.3
README
通过增加一些特定于 Interitty 项目的功能扩展标准 Symfony/Console。
需求
- PHP >= 8.3
安装
安装 interitty/console 的最佳方式是使用 Composer
composer require interitty/console
然后在 Nette 配置 文件中注册扩展
# app/config/config.neon
extensions:
console: Interitty\Console\Nette\DI\ConsoleExtension(%consoleMode%)
特性
Interitty/Console
为标准 Symfony/Console
库提供了额外的功能。
控制台输出
BaseCommand
类提供了 write
和 writeError
方法,允许分别将内容写入标准输出和标准错误输出,无需将 OutputInterface
对象传递到每个方法。
protected function foo(): void
{
// outputs multiple lines to the console (adding PHP_EOL at the end of each line)
$this->write([
'User Creator',
'============',
'',
]);
// the value returned by someMethod() can be an iterator (https://php.ac.cn/iterator)
// that generates and returns the messages with the 'yield' PHP keyword
$this->write($this->someMethod());
// outputs a message followed by a PHP_EOL
$this->write('Whoa!');
// outputs a message without adding a PHP_EOL at the end of the line
$this->write('You are about to ', false);
$this->write('create a user.', false);
// outputs a message to standard error output
$this->writeError('<error>big bada bum</error>');
}
这是通过存储的 InputInterface
和 OutputInterface
对象实现的,这些对象可以通过 getInput
、getOutput
和 getErrorOutput
方法访问。
异常处理器
当在 execute
过程中抛出 Exception
或任何 Throwable
对象时,有一个标准的 processException
方法,将异常消息转换为标准错误输出消息。当设置 Debug verbosity mode 时,它还会记录跟踪日志。
延迟加载
ConsoleExtension
扩展会自动使用简单的实现 LazyCommandLoader
绑定所有注册的类型为 Symfony\Component\Console\Command\Command
的服务。
使用 AsCommand
属性定义的值用作命令名称。
use Interitty\Console\BaseCommand;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'app:dummy')]
class DummyCommand extends BaseCommand
{
}
然而,许多现有的类仍然需要开始使用此属性。将这些名称设置为不同的值可能也有帮助。在这些情况下,在定义服务时使用所谓的 tags 是可能的。
services:
commands.dummy:
class: App\DummyCommand
tags: [console.command: app:dummy]
# or
tags: [console.command: {name: app:dummy}]
进度条工厂
工厂方法 createProgressBar
可用于更容易地访问 进度条。
protected function processExecute(): int
{
$data = $this->getData();
$progressBar = $this->createProgressBar($data->count());
$progressBar->start();
foreach($data as $item) {
// Do some logic here
$progressBar->advance();
}
$progressBar->finish();
return self::SUCCESS;
}