circli / console
symfony console 的包装,以更好地支持容器
2.2.0
2024-06-14 09:09 UTC
Requires
- php: ^8.1
- symfony/console: ^5.0||^6.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^10.0
- psr/container: ^1.0
README
我创建这个包是为了让 symfony console 应用的初始化更轻量。如果一个类会自动连接到远程服务,并且需要在列出命令或运行不连接到远程服务的操作时执行这个操作,那就会有点烦人。所以我将定义和命令分成两部分:一部分是定义,另一部分是命令。命令只有在需要时才会初始化。
安装
composer require circli/console
使用
定义
定义对象处理与命令调用相关的所有内容。并且 必须 扩展 \Circli\Console\Definition
。
命令
命令可以是任何 callable
,并且 必须 返回一个整数。
所以任何你想用作命令的类都需要实现 __invoke(InputInterface $input, OutputInterface $output): int
。
最基本的定义
class ExampleCommandDefinition extends \Circli\Console\Definition { protected function configure(): void { $this->setName('example:command'); $this->setCommand(function($input, $output) { return 0; }); } } $application = new Application(); $application->addDefinition(new ExampleCommandDefinition()); $application->run();
使用自定义输入
你可以将输入转换为自定义输入类型,以获得更好的类型提示和控制传入命令的内容。
class ExampleInput extends \Circli\Console\AbstractInput { public function getFrom(): \DateTimeInterface { $rawDate = $this->getArgument('from') ?: 'now'; return new \DateTimeImmutable($rawDate); } } class ExampleCommandDefinition extends \Circli\Console\Definition { protected function configure(): void { $this->setName('example:command'); $this->addArgument('from', InputArgument::REQUIRED); $this->setCommand(function(ExampleInput $input, $output) { $from = $input->getFrom(); return 0; }); } public function transformInput(InputInterface $input, OutputInterface $output): InputInterface { return new ExampleInput(); } }
使用 psr 容器
这是一个基本的实现,以实现延迟初始化。
如果你传递容器命令解析器,它会在需要时尝试解析命令。
如果你不想以这种方式传递容器,你可以编写自己的解析逻辑
use Circli\Console\Application; use Circli\Console\ContainerCommandResolver; use Circli\Console\Definition; $application = new Application(new ContainerCommandResolver($psr11container)); $application->addDefinition(new class extends Definition { protected function configure(): void { $this->setName('example:command'); $this->setCommand('keyInContainer'); } }); $application->run();
与常规 Symfony console 一起使用
use Symfony\Component\Console\Application; use Circli\Console\Command; $application = new Application(); $application->add(new \Circli\Console\Command(new CmdDefinition())); $application->run();
许可
MIT 许可证 (MIT)。请参阅 许可文件 获取更多信息。