萬盛學電腦網

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

PHP 檔案操作類:支援多行寫入、模式控制與路徑管理

類別設計

<?php
class FileWriter
{
    private string $path;
    private string $mode = 'a';
    private string $content = '';

    public function __construct(string $path, string $mode = 'a', string $content = '')
    {
        $this->path = $path;
        $this->mode = $mode;
        $this->content = $content;
    }

    public function setPath(string $path): self { $this->path = $path; return $this; }
    public function setMode(string $mode): self { $this->mode = $mode; return $this; }
    public function setContent(string $content): self { $this->content = $content; return $this; }

    public function write(): bool
    {
        $dir = dirname($this->path);
        if (!is_dir($dir) && !mkdir($dir, 0775, true)) return false;

        $fp = fopen($this->path, $this->mode);
        if (!$fp) return false;

        // 支援陣列或字串(以換行分割)
        $lines = is_array($this->content) ? $this->content : explode("\n", $this->content);
        foreach ($lines as $line) {
            fwrite($fp, rtrim($line) . PHP_EOL);
        }
        fclose($fp);
        return true;
    }

    // 靜態快捷方法
    public static function append(string $path, string $line): bool
    {
        return (new self($path, 'a', $line))->write();
    }
}
?>

使用範例

// 單行追加
FileWriter::append('/var/log/app.log', date('c') . ' User login: ' . $userId);

// 多行一次寫入
$lines = [
    'ERROR: Database connection failed',
    'Host: db-01',
    'Retry: 3',
];
(new FileWriter('/var/log/error.log', 'a', $lines))->write();

// 覆寫模式
(new FileWriter('/tmp/config.ini', 'w', "debug=true\nenv=prod"))->write();

進階擴充建議

  • 鎖定機制:flock($fp, LOCK_EX) 寫入前加鎖、寫入後釋放。
  • 日誌輪轉:依日期/大小分割檔案,搭配 logrotate。
  • 結構化日誌:改輸出 JSON Lines,便於 ELK/Loki 收集分析。
  • 非同步寫入:高頻日誌可寫入 Redis List / Kafka,背景 Worker 落盤。
copyright © 萬盛學電腦網 all rights reserved