mallardduck/immutable-read-file

一个为 PHP 的文件函数制作 '不可变' 包装器的实验。

1.0.0 2021-04-24 23:09 UTC

This package is auto-updated.

Last update: 2024-08-25 06:37:19 UTC


README

Latest Stable Version Total Downloads License codecov Coverage Status Latest Unstable Version

如果你曾经使用过 fopen/SplFileObject 并且希望结果具有幂等性1,这就是方法。

使用这个库,你将获得一个基本 SplFileObject 的只读不可变包装器——这实际上是 OOP fopen。

你可能很少会用到这个,但如果需要,你就会知道……而且它可能非常有用。

1 = 从技术上讲是因为包装器跟踪一个“规范”位置以始终从中工作。

安装

您可以通过 composer 安装此软件包

composer require mallardduck/immutable-read-file

使用方法

use MallardDuck\ImmutableReadFile\ImmutableFile;

$fileName = __DIR__ . '/tests/stubs/json.txt'; // CONTENT: {"hello": "world"}

$step1 = ImmutableFile::fromFilePath($fileName);
echo $step1->fgetc(); // { - The first character of your file
echo $step1->fgetc(); // { - The first character of your file, again
$step2 = $step1->advanceBytePosition(); // A new r/o immutable entity advanced a single byte by default.
echo $step2->fgetc(); // " - The second character of your file
echo $step2->fgetc(); // " - The second character of your file, again

为什么!我不明白?

所以,你已经被告知这只会很少有用——但一旦有用,它就非常非常有用。你真的读对了吗?

理解何时使用此功能的主要方法是理解它与 fopenSplFileObject 的不同之处。由于在默认行为不希望的情况下,这将很有用。

所以,请自己看看!示例...

fopen 默认工作方式

使用第二个 fopenfseek 的目的是模拟使用示例中 $step1->advanceBytePosition() 做的事情。

$fileName = __DIR__ . '/tests/stubs/json.txt'; // CONTENT: {"hello": "world"}

$step1 = fopen($fileName, 'r');
echo fgetc($step1) . PHP_EOL; // { - The first character of your file
echo fgetc($step1) . PHP_EOL; // " - The second character of your file
$step2 = fopen($fileName, 'r');
fseek($step2, 1);
echo fgetc($step2) . PHP_EOL; // " - The second character of your file
echo fgetc($step2) . PHP_EOL; // h - The third character of your file

SplFileObject 默认工作方式

使用第二个 new SplFileObject$step2->fseek(1) 的目的是模拟使用示例中 $step1->advanceBytePosition() 做的事情。

$fileName = __DIR__ . '/tests/stubs/json.txt'; // CONTENT: {"hello": "world"}

$step1 = new SplFileObject($fileName, 'r');
echo $step1->fgetc() . PHP_EOL; // { - The first character of your file
echo $step1->fgetc() . PHP_EOL; // " - The second character of your file
$step2 = new SplFileObject($fileName, 'r');
$step2->fseek(1);
echo $step2->fgetc() . PHP_EOL; // " - The second character of your file
echo $step2->fgetc() . PHP_EOL; // h - The third character of your file

总结

比较 fopenSplFileObject 的工作方式,我们可以看出它们在功能上彼此相同。然而,这也突出了它们与 ImmutableReadFile 的不同。

当你使用返回内容的 fopen/SplFileObject 的方法时,当前的光标位置会增加。这意味着当你在这些方法上运行 fgetc 时,你总是会得到:下一个字符或 EOF。

然而,对于 ImmutableReadFile,这些方法不会影响光标位置。这意味着如果你运行 fgetc,你总是会得到相同的精确字符。只有当你显式地前进字节位置时,你才会得到一个新的字符。那时,你实际上得到了一个新的 ImmutableFile 实例。

测试

composer test

变更日志

有关最近更改的更多信息,请参阅 CHANGELOG

贡献

有关详细信息,请参阅 CONTRIBUTING

安全漏洞

有关如何报告安全漏洞的更多信息,请参阅 我们的安全策略

鸣谢

许可协议

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件