控制台应用程序
控制台应用程序主要用于创建实用工具、后台处理和维护任务。
入门
If you're using yiisoft/app or yiisoft/app-api, console support is already included. You can access the entry point as:
./yiiIf you want a standalone console-only application, use the yiisoft/app-console project template:
sh
composer create-project yiisoft/app-console your-projectTo add console support to an existing project from scratch, refer to the yiisoft/yii-console package documentation.
开箱即用只有 serve 命令可用。它启动 PHP 内置 Web 服务器在本地提供应用程序服务。
命令使用 symfony/console 执行。要创建自己的控制台命令,您需要定义一个命令:
php
<?php
namespace App\Command\Demo;
use Symfony\Component\Console\Attribute\AsCommand;
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;
use Yiisoft\Yii\Console\ExitCode;
#[AsCommand(
name: 'demo:hello',
description: 'Echoes hello',
)]
class HelloCommand extends Command
{
public function configure(): void
{
$this
->setHelp('This command serves for demo purpose')
->addArgument('name', InputArgument::OPTIONAL, 'Name to greet', 'anonymous');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$name = $input->getArgument('name');
$io->success("Hello, $name!");
return ExitCode::OK;
}
}现在在 config/params.php 中注册该命令:
php
return [
'yiisoft/yii-console' => [
'commands' => [
'demo:hello' => App\Demo\HelloCommand::class,
],
],
];完成后,命令可以通过以下方式执行:
./yii demo:hello Alice