使用enygma/cmd如何簡化命令行參數解析

在開發命令行工具時,經常需要處理用戶通過命令行傳遞的各種參數。手動解析 $_SERVER[‘argv’] 數組不僅代碼冗長,而且容易出錯。例如,需要區分普通參數、帶值的參數、以及各種簡寫形式,處理起來非常麻煩。此外,為了讓命令行工具更加友好,還需要提供格式化的輸出,例如成功、警告、錯誤等不同類型的消息。 composer在線學習地址:學習地址enygma/cmd 庫正是為了解決這些問題而誕生的。它提供了一個簡單易用的 Command 類,可以將 $_SERVER[‘argv’] 解析為鍵值對,并且支持設置默認值和必需參數。同時,它還提供了一個 Output 類,可以方便地輸出格式化的消息。

安裝

使用 Composer 安裝 enygma/cmd 非常簡單:

composer require enygma/cmd

使用示例

以下是一個簡單的示例,展示了如何使用 enygma/cmd 解析命令行參數

<?php  require_once 'vendor/autoload.php'; use CmdCommand;  $cmd = new Command(); $args = $cmd->execute($_SERVER['argv']);  echo 'RESULT: '.var_export($args, true)."n";  ?>

假設我們執行以下命令:

php test.php plain-arg --foo --bar=baz

enygma/cmd 會將參數解析為以下數組:

Array (     [0] => plain-arg     [foo] => 1     [bar] => baz )

設置默認值和必需參數

enygma/cmd 還支持設置默認值和必需參數,這使得命令行工具更加健壯。

<?php  require_once 'vendor/autoload.php'; use CmdCommand;  $cmd = new Command(); $config = [   'default' => ['foo' => true],   'required' => ['bar'] ];  $args = $cmd->execute($_SERVER['argv'], $config);  echo 'RESULT: '.var_export($args, true)."n";  ?>

在這個例子中,如果用戶沒有傳遞 –foo 參數,那么 $args[‘foo’] 的值將會是 true。如果用戶沒有傳遞 –bar 參數,execute() 方法將會拋出一個異常。

格式化輸出

enygma/cmd 還提供了一個 Output 類,可以方便地輸出格式化的消息。

<?php  require_once 'vendor/autoload.php'; use CmdOutput;  $out = new Output(); $out->success('Success message goes here!');  $out->warning('Warning message goes here!');  $out->Error('Error message goes here!'); ?>

Output 類提供了 success()、warning()、info() 和 error() 等方法,可以輸出不同類型的消息。你還可以自定義消息類型:

<?php require_once 'vendor/autoload.php'; use CmdOutput;  $out = new Output(); $out->addType('custom1', 'white', 'blue');  $out->custom1('A custom message'); ?>

總而言之,enygma/cmd 是一個非常實用的命令行工具庫,它可以極大地簡化命令行參數解析和格式化輸出,提高開發效率,使命令行工具更加健壯和友好。

? 版權聲明
THE END
喜歡就支持一下吧
點贊13 分享