amsify42/php-command-line

这是一个用于处理命令行参数的PHP包

1.0 2020-04-30 17:00 UTC

This package is not auto-updated.

Last update: 2024-09-27 13:48:49 UTC


README

这是一个用于处理命令行参数的PHP包。

安装

$ composer require amsify42/php-command-line

目录

  1. 介绍
  2. 获取参数
  3. 双短横线参数
  4. 转换为字符串
  5. CLI任务

1. 介绍

Amsify42\CommandLine\CommandLine 帮助获取以任何格式传递的cli参数。

php file.php 42 amsify "some description"

php file.php -id 42 -name amsify -desc "some description"

php file.php -id=42 -name=amsify -desc="some description"

2. 获取参数

要获取所有传递的参数,可以调用此方法

use \Amsify42\CommandLine\CommandLine;
CommandLine::getParams();

或使用辅助方法

cli_get_params();

要获取特定键参数

CommandLine::getParam('id');

cli_get_param('id');

要检查cli参数是否存在

CommandLine::isParam('id');

cli_is_param('id');

如果存在,则返回 true,否则返回 false

3. 双短横线参数

辅助类还可以检测使用双短横线传递的参数名称

php file.php --global

我们可以使用相同的 isParam 方法来检查是否传递了 全局 参数。

4. 转换为字符串

我们还可以使用此方法将所有传递的cli参数转换为字符串。

echo CommandLine::toString();

echo cli_to_string();

5. CLI任务

在任意目录下创建一个类,例如:/app/Task/

<?php

namespace App\Task;

use Amsify42\CommandLine\Task\BaseTask;

class Test extends BaseTask
{
    public function init()
    {
     	printMsg("Doing something");   
    }
}

您可以从控制台运行此脚本,就像在其他文件中一样 test.php

<?php
require_once __DIR__.'/vendor/autoload.php';
\Amsify42\CommandLine\Task::run(\App\Task\Test::class);

然后运行此文件

php test.php

如果脚本文件名直接从命令行传递

require_once __DIR__.'/vendor/autoload.php';
$task = new \Amsify42\CommandLine\Task();
$task->process();

并使用任务文件名运行文件

php test.php App\Task\Test

要程序化运行脚本,可以使用此方法

\Amsify42\CommandLine\Task::run(\App\Task\Test::class);

要在后台异步运行脚本,需要将第3个参数传递为 true

\App\Console::run(\App\Task\Test::class, [], true);

参数/验证

您还可以像这样将cli参数与脚本一起传递

php test.php App\Task\Test -id 1 -name Kyro

通过方法

\Amsify42\CommandLine\Task::run(\App\Task\Test::class, ['id' => 1, 'name' => 'Kyro']);

并在脚本中收集这些参数

<?php

namespace App\Task;

use Amsify42\CommandLine\Task\BaseTask;

class Test extends BaseTask
{
    public function init()
    {
    	$id 	= $this->input('id');
    	$name 	= $this->input('name');
     	// do the remaining
    }
}

要验证和检查参数是否存在,您可以这样做

public function init()
{
	$this->validate(['id', 'name']);
 	// do the remaining
}

如果验证失败,则后续脚本将不会执行。