易于使用的CLI驱动PHP应用程序。

6.0.1 2023-08-29 13:34 UTC

This package is auto-updated.

Last update: 2024-09-29 15:52:02 UTC


README

在Packagist上查看

District5\Cli

最初来自OhConsole项目。

Cli是一个简单的接口,通过将命令抽象成独立的类来创建高级PHP CLI应用程序。

Composer

{
    "repositories":[
        {
            "type": "vcs",
            "url": "git@github.com:district-5/php-cli.git"
        }
    ],
    "require": {
        "district-5/cli": "*"
    }
}

理论

参数被转换为命名空间。最终的路线类必须以Route结尾。例如,一个完全限定的类名SomeApp\Foo\Bar\ProcessMyTasksRoute可以用some-app foo bar process-my-tasks来调用。

一个更简单的例子是Config\Get\UrlRoute,可以用config get url来调用。

快速开始

要快速开始,首先创建您的核心命令文件。通常这可以是bin/console。此文件应包含如下内容:

<?php
use District5\Cli\CliApp;

// Map any injectables that you want to pass
$injectables = [
    'config' => [
        // Put any configuration here.
    ]
];

// Start CliApp
$cliApp = CliApp::createApp($argv, $injectables); // or `$command = new CliApp($argv, $injectables);`

// Optionally, to support PSR-4 namespaces you can set a namespace prefix:
// $cliApp->setPsrNamespacePrefix('FooBar');

// By default, routes appended with 'Route' will be looked for. You can change this to be something else:
// $cliApp->setClassAppend('Command'); // would look for a class called 'XxxxxCommand'

// Run CliApp
$cliApp->run();

示例

<?php
namespace MyApp;

use District5\Cli\CliCommand;

/**
 * Class ExampleOneRoute
 */
class ExampleOneRoute extends CliCommand
{
    public function run()
    {
        $this->outputInfo('Running Example One');
        $this->outputInfo('--------');
        $this->outputInfo('Single line');
        $this->outputInfo(array('This', 'is', 'an', 'array'));
        $this->outputError('Single error line!');
        $this->outputError(array('This', 'is', 'also', 'an', 'array'));
        $this->outputInfo('--------');
        
        if ($this->getArgument(0) !== null) {
            $this->outputInfo('You sent in: ' . $this->getArgument(0));
        }
    }
}

一旦设置了示例,调用主脚本(见下文),并传递在PHP文件中定义的命令之一。

php ./console.php my-app example-one

添加一些参数..

您可以将两种不同的参数类型传递到此脚本中。

  • 简单 - 数字 - ./script.php command arg1 arg2 ...
    • 可以通过getArgument(0)getArgument(1)获取。
  • 高级 - 命名 - ./script.php command --foo=bar --hello=world ...
    • 参数通过CliArgvs处理。您可以在命令中通过调用getCliArgvs来获取此对象。
    • 可以通过getArgument('foo')getArgument('hello')获取。
    • 您可以将它们链接到数组中,调用getArgument('foo')将返回一个数组。
      • ./script.php command --foo=bar --foo=another --foo=andAnother

要将参数发送到路由,只需将它们附加即可。例如,将hello附加到上述脚本末尾,将允许您在命令中使用getArgument(0)方法来检索参数。

  • 在路由中

    if ($this->getArgument(0) !== null) {
        $this->outputInfo('You passed in: ' . $this->getArgument(0));
    }
  • Bash

    php ./console.php my-app example-one hello

以下是一个您可以使用它开始的示例console.php

<?php
use District5\Cli\CliApp;

$injectables = [
    'config' => [
        'db.name' => 'MyDatabaseName',
        'db.user' => 'root',
        'db.password' => 'password',
    ]
];

$cliApp = CliApp::createApp($argv, $injectables);
$cliApp->run();