amphp/file
Non-blocking file I/O for PHP 8.1+ in the AMPHP ecosystem. Read/write files or stream via async file handles while keeping apps responsive. Uses multi-process by default, with optional eio/uv/parallel drivers when available.
Begin by installing via Composer: composer require amphp/file. This package provides async, non-blocking file I/O for PHP applications using Amp’s event loop—ideal for concurrent file operations (e.g., reading many log files or serving static assets in an HTTP server). Start by using Amp\File\read() for simple file reads or Amp\File\write() for writes, ensuring you call Amp\Loop::run() to execute the async context. For example:
Amp\Loop::run(function () {
$content = yield Amp\File\read('data.txt');
echo $content;
});
Check the examples/ directory in the repo for minimal use cases like streaming files, listing directories concurrently, or leveraging file locking.
Amp\Map\promise() or Amp\All\promise() with multiple file operations to handle many files in parallel, avoiding blocking the event loop.Amp\ByteStream\resourceToStream() to stream file contents without loading them fully into memory—ideal for APIs or proxies.Amp\Http\Server\Response and Amp\File\read() to serve files efficiently in async HTTP servers (e.g., with Amp’s http-server or ReactPHP bridges).try/catch around yields; Amp\File\Exception\IOException is thrown for I/O issues—log context (e.g., path, operation) for traceability.Amp\File\open() to get a File instance, then call $file->lock($exclusive = false) (shared lock) or $file->lock($exclusive = true) (exclusive lock) before reading/writing, and $file->unlock() afterward. For non-blocking attempts, use tryLock() (returns bool) and handle accordingly. Essential for coordinating access in concurrent workers or multi-process environments.read() calls still load full contents into memory. Use open() + read() in chunks (e.g., via Amp\ByteStream\ResourceInputStream) for large files.realpath() or __DIR__ to avoid ambiguity.DIRECTORY_SEPARATOR is respected, but Amp internally normalizes paths—avoid manual concatenation ($path . '/' . $file); use Amp\File\pathJoin() instead.Amp\Artax\Lock.Amp\Loop::run()—don’t forget to handle async boundaries or consider wrapping in jobs.flock()); never assume mutual exclusion on systems lacking proper lock support (e.g., some network filesystems). Prefer tryLock() over lock() in high-concurrency contexts to avoid indefinite blocking—combine with retry logic if needed.ParallelFilesystemDriver now uses LimitedWorkerPool internally. You rarely need to customize this, but if you do, use DelegateWorkerPool to reuse an existing pool while capping concurrency. The getWorkerLimit() setting directly affects file operation parallelism.How can I help you explore Laravel packages today?