fostam/file

为 PHP 函数如 `fopen()`、`fgets()` 提供便捷封装,支持面向对象的使用方式,并通过异常处理错误而不是返回结果。

v1.0.0 2021-12-29 09:25 UTC

This package is auto-updated.

Last update: 2024-09-28 22:26:14 UTC


README

File 是一个简单的便捷封装,用于 PHP 函数如 fopen()fgets()。它提供了文件函数的面向对象使用,并通过抛出异常而不是返回结果和 PHP 警告/错误来处理错误。

安装

安装 File 最简单的方式是使用 composer

$> composer require fostam/file

用法

示例:逐行打印文件内容

<?php

use Fostam\File\File;

$reader = new File($filename, File::MODE_READ);

while ($line = $reader->readLine()) {
    print $line;
}

$reader->close();

示例:写入文件

$writer = new File($filename, File::MODE_WRITE_CREATE_OR_TRUNCATE);
$writer->write('test');
$writer->close();

示例:从已知位置恢复读取文件

$reader = new File($filename, File::MODE_READ);

// (read $pos from previous run)

while ($line = $reader->readLine(null, $pos)) {
    // (process $line)
    // (save $pos to resume if interrupted)
}

$reader->close();

错误

所有错误都被捕获并通过抛出异常传递。所有抛出的异常都源自于 Fostam\File\Exception\FileException 类。

参考

方法

打开文件模式

有关模式的描述,请参阅 fopen() 文档

异常

  • FileException
  • OpenFileErrorFileException
  • CloseFileErrorFileException
  • GetPositionErrorFileException
  • SetPositionErrorFileException
  • ReadErrorFileException
  • WriteErrorFileException
  • TruncateErrorFileException
  • FlushErrorFileException
  • ValueErrorFileException
  • LockWouldBlockFileException