PHP Classes

How to Implement PHP Async IO to Access Files Faster with PHP Fibers Using the Package Penelope Asynchronous File Handler using Fibers: Read and write data to files using fibers

Recommend this page to a friend!
  Info   Documentation   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2024-12-09 (3 days ago) RSS 2.0 feedNot enough user ratingsTotal: 3 This week: 3All time: 11,506 This week: 21Up
Version License PHP version Categories
penelope 1.0.0GNU General Publi...8.1Files and Folders, Compression, Perfo..., P...
Description 

Author

This package can read and write data to files using fibers.

It provides a class to read or write data to files synchronously or asynchronously using fibers.

The package can read or write one chunk of data at a time asynchronously.

It also supports compression to write data and decompression to read data using the bzip2 compression algorithm.

The package can handle errors retrying read and write accesses according to a given policy.

Picture of Carlos Artur Curvelo da Matos
  Performance   Level  
Name: Carlos Artur Curvelo da ... <contact>
Classes: 25 packages by
Country: Portugal Portugal
Innovation award
Innovation award
Nominee: 16x

Winner: 2x

Documentation

Penelope ?

PHP Composer PHP 8.2 PHPUnit Tests

A high-performance asynchronous file handling library for PHP, leveraging Fibers for non-blocking I/O operations.

? Overview

Penelope is designed to handle large file operations efficiently by utilizing PHP's Fiber feature for asynchronous processing. It breaks down file operations into manageable chunks, allowing for better memory management and improved performance, especially for large files.

Why Penelope?

  • Memory Efficient: Process large files without loading them entirely into memory
  • Non-Blocking: Leverage PHP Fibers for asynchronous operations
  • Flexible: Support for both synchronous and asynchronous operations
  • Transformable: Apply custom transformations during read/write operations
  • Progress Tracking: Monitor write progress in real-time
  • Compression Support: Built-in support for gzip, bzip2, and deflate compression
  • Error Resilience: Robust error handling with retry mechanisms and logging

? Requirements

  • PHP 8.1 or higher (Fiber support required)
  • Composer for dependency management
  • PHP Extensions: - `zlib` for gzip/deflate compression - `bz2` for bzip2 compression (optional)

? Installation

composer require cmatosbc/penelope

# For bzip2 support (Ubuntu/Debian)
sudo apt-get install php-bz2

? Usage

Basic File Reading

use Penelope\AsyncFileHandler;

// Create a handler instance
$handler = new AsyncFileHandler('large_file.txt', 'r');

// Synchronous read
$content = $handler->readSync();

// Asynchronous read
$fiber = $handler->readAsync();
$content = '';

$chunk = $fiber->start();
if ($chunk !== null) {
    $content .= $chunk;
}

while ($fiber->isSuspended()) {
    $chunk = $fiber->resume();
    if ($chunk !== null) {
        $content .= $chunk;
    }
}

Compression Support

use Penelope\Compression\CompressionHandler;

// Create a compression handler (gzip, bzip2, or deflate)
$compression = new CompressionHandler('gzip', 6); // level 6 compression

// Compress data
$compressed = $compression->compress($data);

// Decompress data
$decompressed = $compression->decompress($compressed);

// Get file extension for compressed files
$extension = $compression->getFileExtension(); // Returns .gz for gzip

Error Handling with Retries

use Penelope\Error\ErrorHandler;
use Penelope\Error\RetryPolicy;
use Psr\Log\LoggerInterface;

// Create a retry policy with custom settings
$retryPolicy = new RetryPolicy(
    maxAttempts: 3,        // Maximum number of retry attempts
    delayMs: 100,          // Initial delay between retries in milliseconds
    backoffMultiplier: 2.0, // Multiplier for exponential backoff
    maxDelayMs: 5000       // Maximum delay between retries
);

// Create an error handler with custom logger (optional)
$errorHandler = new ErrorHandler($logger, $retryPolicy);

// Execute an operation with retry logic
try {
    $result = $errorHandler->executeWithRetry(
        function() {
            // Your operation here
            return $someResult;
        },
        'Reading file chunk'
    );
} catch (\RuntimeException $e) {
    // Handle final failure after all retries
}

Combining Features

use Penelope\AsyncFileHandler;
use Penelope\Compression\CompressionHandler;
use Penelope\Error\ErrorHandler;
use Penelope\Error\RetryPolicy;

// Set up handlers
$compression = new CompressionHandler('gzip');
$retryPolicy = new RetryPolicy(maxAttempts: 3);
$errorHandler = new ErrorHandler(null, $retryPolicy);
$fileHandler = new AsyncFileHandler('large_file.txt', 'r');

// Read and compress file with retry logic
$errorHandler->executeWithRetry(
    function() use ($fileHandler, $compression) {
        $fiber = $fileHandler->readAsync();
        $compressedContent = '';
        
        // Start reading
        $chunk = $fiber->start();
        if ($chunk !== null) {
            $compressedContent .= $compression->compress($chunk);
        }
        
        // Continue reading
        while ($fiber->isSuspended()) {
            $chunk = $fiber->resume();
            if ($chunk !== null) {
                $compressedContent .= $compression->compress($chunk);
            }
        }
        
        // Write compressed content
        file_put_contents('output.gz', $compressedContent);
    },
    'Compressing file'
);

? Use Cases

1. Large File Processing

Perfect for processing large log files, data exports, or any situation where memory efficiency is crucial:

$handler = new AsyncFileHandler('large_log.txt', 'r');
$fiber = $handler->readAsync();

// Process line by line without loading entire file
while ($chunk = $fiber->resume()) {
    // Process chunk
    analyzeLogData($chunk);
}

2. File Compression and Archiving

  • Compress large log files for archival
  • Create compressed backups of data files
  • Stream compressed data to remote storage
  • Process and compress multiple files in parallel

3. Error-Resilient Operations

  • Retry failed network file transfers
  • Handle intermittent I/O errors gracefully
  • Log detailed error information for debugging
  • Implement progressive backoff for rate-limited operations

? Performance

Based on our benchmarks with a 100MB file:

  • Async Read: ~3.4x faster than synchronous read
  • Async Write: Comparable to synchronous write
  • Memory Usage: Consistent across operations
  • Chunk Size: Default 8KB (configurable)

? Testing

composer install
./vendor/bin/phpunit --testdox

? Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

? License

This project is licensed under the GNU General Public License v3.0 - see the LICENSE file for details. This means:

  • You can freely use, modify, and distribute this software
  • If you modify and distribute this software, you must: * Make your modifications available under GPL-3.0 * Include the original copyright notice * Include the full text of the GPL-3.0 license * Make your source code available

?? Important Notes

  • Requires PHP 8.1+ for Fiber support
  • Performance may vary based on file size and system configuration
  • For optimal performance, adjust chunk size based on your use case

? Links


  Files folder image Files (16)  
File Role Description
Files folder image.github (1 directory)
Files folder imagesrc (1 file, 2 directories)
Files folder imagetests (3 files, 2 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files (16)  /  .github  
File Role Description
Files folder imageworkflows (2 files)

  Files folder image Files (16)  /  .github  /  workflows  
File Role Description
  Accessible without login Plain text file composer.yml Data Auxiliary data
  Accessible without login Plain text file phpunit.yml Data Auxiliary data

  Files folder image Files (16)  /  src  
File Role Description
Files folder imageCompression (2 files)
Files folder imageError (2 files)
  Plain text file AsyncFileHandler.php Class Class source

  Files folder image Files (16)  /  src  /  Compression  
File Role Description
  Plain text file CompressionHandler.php Class Class source
  Plain text file CompressionInterface.php Class Class source

  Files folder image Files (16)  /  src  /  Error  
File Role Description
  Plain text file ErrorHandler.php Class Class source
  Plain text file RetryPolicy.php Class Class source

  Files folder image Files (16)  /  tests  
File Role Description
Files folder imageCompression (1 file)
Files folder imageTestListener (1 file)
  Plain text file AsyncFileHandlerTest.php Class Class source
  Accessible without login Plain text file bootstrap.php Aux. Configuration script
  Plain text file PerformanceTest.php Class Class source

  Files folder image Files (16)  /  tests  /  Compression  
File Role Description
  Plain text file CompressionHandlerTest.php Class Class source

  Files folder image Files (16)  /  tests  /  TestListener  
File Role Description
  Plain text file PenelopeEventSubscriber.php Class Class source

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads Download Rankings  
 100%
Total:3
This week:3
All time:11,506
This week:21Up