簡體   English   中英

PHP-CLI記錄進度/輸出和捕獲錯誤的最佳實踐

[英]PHP-CLI Best Practice for Logging Progress/Output and Catching Errors

我正在編寫一個PHP CLI工具。 該工具具有許多可用的命令行選項。 這將是一堂課。 我將加載一個實例,並使用所有傳入的參數運行命令。

在捕獲信息消息的過程中以及捕獲錯誤和停止錯誤並輸出到屏幕時,最好的方法是什么?

什么是理想的PHP CLI示例?

我使用如下模板作為模板(用於足夠簡單的控制台腳本):

$inputFile = null;
$outputFile = null;
try {
    // Checking command-line arguments
    if (1 === $argc) {
        throw new Exception('Missing input file path.');
    }

    $inputFilePath = $argv[1];
    if (!file_exists($inputFilePath) || !is_readable($inputFilePath)) {
        throw new Exception('Input file does not exist or cannot be read.');
    }

    $inputFile = fopen($inputFilePath, 'r');

    if (2 < $argc) {
        $outputFilePath = $argv[2];
        if (!is_writable($outputFilePath)) {
            throw new Exception('Cannot write to output file.');
        }

        $outputFile = fopen($outputFilePath, 'w');
    } else {
        $outputFile = STDOUT;
    }

    // Do main process (reading data, processing, writing output data)
} catch (Exception $e) {
    // Show usage info, output error message

    fputs(STDERR, sprintf('USAGE: php %s inputFilePath [outputFilePath]', $argv[0]) . PHP_EOL);
    fputs(STDERR, 'ERROR: ' . $e->getMessage() . PHP_EOL);
}

// Free resources

if ($inputFile) {
    fclose($inputFile);
}

if ($outputFile) {
    fclose($outputFile);
}

我更喜歡使用一種觀察者模式進行處理,並將錯誤處理留給控制台應用程序:

class ExampleService
{
    /**
     * @var array
     */
    private $params;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    /**
     * @param callable|null $listener
     */
    public function execute(callable $listener = null)
    {
        foreach (['long', 'term', 'loop'] as $item) {
            // do complex stuff
            $listener && $listener($item);
        }
    }
}

require_once __DIR__ . '/vendor/autoload.php';

use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

$app = new Application;
$app->add($command = new Command('example'));

$command->addOption('opt1');
$command->addArgument('arg1');
$command->setCode(function(InputInterface $input, OutputInterface $output) {
    $service = new ExampleService($input->getOptions() + $input->getArguments());
    $service->execute(function($messages) use($output){
        $output->writeln($messages);
    });
});

$app->run();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM