cakephp/console

使用CakePHP构建漂亮的控制台应用程序


README

Total Downloads License

CakePHP控制台库

此库提供了一套框架,用于从一组命令构建命令行应用程序。它提供了定义选项和参数解析器以及分发命令的抽象。

安装

您可以通过Composer安装它。在您的项目中

composer require cakephp/console

入门

首先,定义一个入口点脚本和Application类,该类定义启动逻辑并绑定您的命令。让我们将我们的入口点脚本放在bin/tool.php

#!/usr/bin/php -q
<?php
// Check platform requirements
require dirname(__DIR__) . '/vendor/autoload.php';

use App\Application;
use Cake\Console\CommandRunner;

// Build the runner with an application and root executable name.
$runner = new CommandRunner(new Application(), 'tool');
exit($runner->run($argv));

对于我们的Application类,我们可以从以下内容开始

<?php
namespace App;

use App\Command\HelloCommand;
use Cake\Core\ConsoleApplicationInterface;
use Cake\Console\CommandCollection;

class Application implements ConsoleApplicationInterface
{
    /**
     * Load all the application configuration and bootstrap logic.
     *
     * @return void
     */
    public function bootstrap(): void
    {
        // Load configuration here. This is the first
        // method Cake\Console\CommandRunner will call on your application.
    }


    /**
     * Define the console commands for an application.
     *
     * @param \Cake\Console\CommandCollection $commands The CommandCollection to add commands into.
     * @return \Cake\Console\CommandCollection The updated collection.
     */
    public function console(CommandCollection $commands): CommandCollection
    {
        $commands->add('hello', HelloCommand::class);

        return $commands;
    }
}

接下来,我们将构建一个非常简单的HelloCommand

<?php
namespace App\Command;

use Cake\Console\Arguments;
use Cake\Console\BaseCommand;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;

class HelloCommand extends BaseCommand
{
    protected function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
    {
        $parser
            ->addArgument('name', [
                'required' => true,
                'help' => 'The name to say hello to',
            ])
            ->addOption('color', [
                'choices' => ['none', 'green'],
                'default' => 'none',
                'help' => 'The color to use.'
            ]);

        return $parser;
    }

    public function execute(Arguments $args, ConsoleIo $io): ?int
    {
        $color = $args->getOption('color');
        if ($color === 'none') {
            $io->out("Hello {$args->getArgument('name')}");
        } elseif ($color == 'green') {
            $io->out("<success>Hello {$args->getArgument('name')}</success>");
        }

        return static::CODE_SUCCESS;
    }
}

接下来,我们可以使用php bin/tool.php hello Syd来运行我们的命令。要了解更多关于我们在这个示例中使用的各种功能的信息,请阅读文档