萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 命令行模式 (CLI) 完全指南:參數解析、標準輸入/輸出、常用選項、守護進程

CLI SAPI 核心特性

  • **無輸出緩衝**:默認 `output_buffering = 0`,`echo` 直接輸出
  • **無超時限制**:`max_execution_time = 0` (無限)
  • **當前目錄**:腳本所在目錄而非 Web 文檔根目錄
  • **參數變量**:`$argc` (參數個數)、`$argv` (參數陣列,`$argv[0]` 為腳本路徑)
  • **標準流**:`STDIN`、`STDOUT`、`STDERR` 常量 (資源句柄)
  • **錯誤輸出**:默認直接輸出到終端,不經 Web 服務器日誌

常用啟動選項

選項說明示例
-r直接執行代碼字符串 (無需 <?php ?>)`php -r 'echo "Hello";'`
-f / 無執行文件`php script.php` / `php -f script.php`
-l語法檢查 (不執行)`php -l script.php`
-i顯示 phpinfo()`php -i | grep memory_limit`
-m列出已加載擴展`php -m | grep redis`
-c指定 php.ini 路徑`php -c /etc/php/8.3/cli/php.ini script.php`
-d運行時覆蓋 ini 設置`php -d memory_limit=512M script.php`
-a交互模式 (REPL)`php -a` → 輸入代碼即時執行
-B / -R / -F / -E處理標準輸入每行/文件 (類 awk)`seq 5 | php -R 'echo $argn*2 . "\n";'`
--分隔 PHP 選項與腳本參數`php script.php -- --env=prod`

參數解析最佳實踐

原生 $argv 簡單處理

<?php
// script.php
if ($argc < 2) {
    die("Usage: php $argv[0]  [options]\n");
}

$command = $argv[1];
$options = [
    'env' => 'dev',
    'verbose' => false,
];

// 簡單解析 --key=value
for ($i = 2; $i < $argc; $i++) {
    if (str_starts_with($argv[$i], '--')) {
        [$key, $val] = array_pad(explode('=', $argv[$i], 2), 2, true);
        $options[substr($key, 2)] = $val === true ? true : $val;
    }
}

echo "Command: $command\n";
echo "Env: {$options['env']}\n";
echo "Verbose: " . ($options['verbose'] ? 'yes' : 'no') . "\n";

專業級:Symfony Console / Laravel Zero (推薦生產項目)

composer require symfony/console

// src/Command/ImportCommand.php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class ImportCommand extends Command
{
    protected static $defaultName = 'import:csv';
    
    protected function configure(): void
    {
        $this->setDescription('導入 CSV 文件到數據庫')
             ->addArgument('file', InputArgument::REQUIRED, 'CSV 文件路徑')
             ->addOption('batch', 'b', InputOption::VALUE_REQUIRED, '批次大小', 1000)
             ->addOption('dry-run', null, InputOption::VALUE_NONE, '僅預覽不入庫');
    }
    
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $file = $input->getArgument('file');
        $batch = $input->getOption('batch');
        $dryRun = $input->getOption('dry-run');
        
        $output->writeln("開始導入: $file");
        // ... 業務邏輯
        return Command::SUCCESS;
    }
}

標準流操作

<?php
// 讀取 STDIN (管道/重定向輸入)
$stdin = fopen('php://stdin', 'r');
while (($line = fgets($stdin)) !== false) {
    $line = trim($line);
    if ($line === '') continue;
    // 處理每行...
    echo "處理: $line\n"; // 輸出到 STDOUT
}
fclose($stdin);

// 區分 STDOUT (正常輸出) 與 STDERR (錯誤/日誌)
// 管道時: php script.php > output.log 2> error.log
fwrite(STDOUT, "正常結果\n");
fwrite(STDERR, "錯誤信息\n");

// 獲取管道輸入內容 (一次性)
$input = file_get_contents('php://stdin');
// 或
$input = stream_get_contents(STDIN);

守護進程 / 長期運行腳本模式

<?php
// daemon.php
declare(ticks=1); // 信號處理需要

$running = true;
$pid = getmypid();

// 信號處理
pcntl_signal(SIGTERM, fn() => $running = false);
pcntl_signal(SIGINT,  fn() => $running = false);
pcntl_signal(SIGHUP,  fn() => reloadConfig()); // 平滑重載

// 寫入 PID 文件 (防止重複啟動)
$pidFile = '/var/run/my_daemon.pid';
if (file_exists($pidFile) && posix_kill((int)file_get_contents($pidFile), 0)) {
    die("已在運行\n");
}
file_put_contents($pidFile, $pid);
register_shutdown_function(fn() => @unlink($pidFile));

// 主循環
while ($running) {
    // 1. 任務邏輯
    processQueue();
    
    // 2. 釋放 CPU (關鍵!否則佔用 100%)
    usleep(100000); // 100ms
    
    // 3. 定期 GC
    if (rand(1, 100) === 1) gc_collect_cycles();
}

function processQueue(): void {
    // Redis/RabbitMQ 取任務處理...
}

function reloadConfig(): void {
    // 重新讀取配置文件...
}

進程管理工具 (生產環境推薦)

工具特點適用
Supervisor進程監控、自動重啟、日誌輪轉、Web UI通用守護進程管理
Systemd系統級、開機自啟、依賴管理、journald 日誌Linux 服務化部署
Swoole/WorkermanPHP 協程服務器、內建進程管理、高併發長連接、WebSocket、高性能服務
Laravel Horizon隊列 Worker 管理、監控、擴縮容Laravel 隊列專用

Systemd 服務單元示例

# /etc/systemd/system/php-worker.service
[Unit]
Description=PHP Queue Worker
After=network.target redis.service

[Service]
Type=simple
User=www-data
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/php artisan queue:work --sleep=3 --tries=3
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal
# 限制資源
MemoryLimit=256M
CPUQuota=50%

[Install]
WantedBy=multi-user.target

常見坑點避雷

  1. Shebang 行:`#!/usr/bin/env php` 必須在文件**第一行**,賦予執行權限 `chmod +x script.php`
  2. 相對路徑:`__DIR__` 基於腳本位置,非 CWD。用 `getcwd()` 獲取執行目錄
  3. 內存洩漏:長運行腳本必須定期 `gc_collect_cycles()`、釋放大變量、避免閉包循環引用
  4. 時區:CLI 不讀取 Web 的 php.ini 時區,顯式 `date_default_timezone_set('Asia/Shanghai')`
  5. 輸出緩衝:`ob_implicit_flush(true)` 或每行 `flush()` 實時輸出日誌
  6. 信號處理:需 `declare(ticks=1)` + `pcntl_signal`,且僅 CLI 支持

實用片段集錦

顏色輸出 (無依賴)

class CliColor {
    public static function color(string $text, string $color): string
    {
        $codes = [
            'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34,
            'magenta' => 35, 'cyan' => 36, 'white' => 37, 'reset' => 0,
        ];
        return "\033[" . $codes[$color] . "m$text\033[0m";
    }
}
echo CliColor::color("成功", "green") . "\n";

進度條

function showProgress(int $current, int $total, int $width = 50): void
{
    $percent = $total ? $current / $total : 1;
    $filled = (int)($width * $percent);
    $bar = str_repeat('█', $filled) . str_repeat('░', $width - $filled);
    $info = sprintf(" %3d%% [%d/%d]", $percent * 100, $current, $total);
    echo "\r[$bar]$info";
    if ($current >= $total) echo "\n";
}

併發進程池 (pcntl_fork)

function parallelExecute(array $tasks, int $maxWorkers = 4): array
{
    $results = [];
    $running = [];
    $taskId = 0;
    
    while ($taskId < count($tasks) || $running) {
        // 啟動新進程
        while (count($running) < $maxWorkers && $taskId < count($tasks)) {
            $pid = pcntl_fork();
            if ($pid === -1) die("fork 失敗");
            if ($pid === 0) {
                // 子進程
                $task = $tasks[$taskId];
                $result = $task();
                exit(json_encode($result)); // 通過退出碼傳遞結果 (簡化)
            }
            $running[$pid] = $taskId++;
        }
        
        // 等待任一子進程結束
        $pid = pcntl_wait($status);
        if ($pid > 0) {
            $results[$running[$pid]] = $status; // 簡化處理
            unset($running[$pid]);
        }
    }
    return $results;
}

總結

PHP CLI 是**腳本自動化、數據遷移、隊列消費、定時任務、微服務側車**的利器。掌握參數解析、標準流、信號處理、進程管理四大核心,配合 Symfony Console 等成熟組件,可構建企業級命令行應用。生產環境**務必使用 Supervisor/Systemd 托管**,避免裸跑 PHP 進程。

copyright © 萬盛學電腦網 all rights reserved