Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Io Component Laravel Package

chigix/io-component

Java-like IO utilities for PHP: base InputStream/OutputStream classes, stdin/stdout helpers, serialization and filesystem stream support. Create custom streams by extending base classes and plug them into file, console, or network IO workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer in your Laravel project:

    composer require chigix/io-component
    

    (Note: Test compatibility with your PHP version; may require PHP 5.4+ due to age.)

  2. First Use Case: CLI Input/Output Replace Laravel’s symfony/console for simple CLI interactions:

    use Chigi\Component\IO\StdInputStream;
    use Chigi\Component\IO\StdOutputStream;
    
    $input = StdInputStream::getInstance();
    $output = StdOutputStream::getInstance();
    
    $output->write("Enter a command: ");
    $command = $input->readLine();
    $output->write("You entered: " . $command . "\n");
    
  3. First Use Case: File Operations Read/write files using stream abstractions:

    use Chigi\Component\IO\FileInputStream;
    use Chigi\Component\IO\FileOutputStream;
    
    // Write to a file
    $output = new FileOutputStream('app/data.log');
    $output->write("Log entry: " . date('Y-m-d H:i:s') . "\n");
    $output->close();
    
    // Read from a file
    $input = new FileInputStream('app/data.log');
    while (($line = $input->readLine()) !== null) {
        echo $line;
    }
    $input->close();
    
  4. Key Classes to Explore

    • Streams: StdInputStream, StdOutputStream, FileInputStream, FileOutputStream.
    • Base Classes: InputStream, OutputStream, BaseStream (for custom implementations).
    • Exceptions: EOFException, IOException.

Implementation Patterns

Workflows

1. CLI Tools with Minimal Dependencies

Use StdInputStream/StdOutputStream in Artisan commands or console scripts to avoid symfony/console:

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Chigi\Component\IO\StdInputStream;
use Chigi\Component\IO\StdOutputStream;

class CustomCommand extends Command {
    protected $input;
    protected $output;

    public function __construct() {
        parent::__construct();
        $this->input = StdInputStream::getInstance();
        $this->output = StdOutputStream::getInstance();
    }

    public function handle() {
        $this->output->write("Confirm (y/n): ");
        $response = $this->input->readLine();
        $this->output->write("Response: " . $response . "\n");
    }
}

2. File System Operations with Stream Abstraction

Replace Laravel’s Storage facade for stream-based file handling (e.g., large files, chunked reads):

use Chigi\Component\IO\FileInputStream;
use Chigi\Component\IO\FileOutputStream;

// Chunked file read (memory-efficient)
$input = new FileInputStream('large_file.csv');
$output = new FileOutputStream('processed_file.csv');

while (($chunk = $input->read(1024)) !== null) {
    $processed = strtoupper($chunk); // Example processing
    $output->write($processed);
}
$input->close();
$output->close();

3. Custom Stream Integration

Extend BaseStream to create domain-specific I/O (e.g., logging to a database, API responses):

use Chigi\Component\IO\OutputStream;

class DatabaseOutputStream extends OutputStream {
    protected function writeString($string) {
        // Log to database instead of stdout
        \DB::table('logs')->insert([
            'message' => $string,
            'created_at' => now(),
        ]);
    }

    public function flush() {
        // Optional: Flush database connection
    }

    public function close() {
        // Cleanup
    }
}

Usage:

$dbOutput = new DatabaseOutputStream();
$dbOutput->write("User logged in\n");
$dbOutput->close();

4. Virtual File System (Mocking)

Use the virtual file system streams (added in v0.1.2) for testing:

use Chigi\Component\IO\VirtualFileSystem;

$vfs = new VirtualFileSystem();
$vfs->createFile('test.txt', "Hello, Virtual FS!\n");

$input = $vfs->getInputStream('test.txt');
echo $input->readLine(); // Output: "Hello, Virtual FS!"

Laravel Integration Tips

1. Register Custom Streams in Service Provider

Bind custom streams to Laravel’s container for dependency injection:

// app/Providers/AppServiceProvider.php
use Illuminate\Support\ServiceProvider;
use Chigi\Component\IO\OutputStream;

class AppServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->bind('custom.logger', function () {
            return new DatabaseOutputStream();
        });
    }
}

Usage in Controllers/Commands:

use Illuminate\Support\Facades\App;

$logger = App::make('custom.logger');
$logger->write("Debug message\n");

2. Testing with Mock Streams

Mock streams in PHPUnit to isolate I/O dependencies:

use Chigi\Component\IO\InputStream;
use Chigi\Component\IO\OutputStream;

public function testCustomStream() {
    $mockInput = $this->createMock(InputStream::class);
    $mockInput->method('readLine')->willReturn("test input");

    $mockOutput = $this->createMock(OutputStream::class);
    $mockOutput->expects($this->once())
               ->method('write')
               ->with("Processed: test input");

    // Inject mocks into your class under test
}

3. Hybrid with Laravel’s Storage

Combine with Laravel’s Storage facade for flexible file handling:

use Illuminate\Support\Facades\Storage;
use Chigi\Component\IO\FileInputStream;

$path = Storage::path('app.log');
$input = new FileInputStream($path);
while (($line = $input->readLine()) !== null) {
    echo $line;
}
$input->close();

4. Error Handling

Wrap stream operations in try-catch blocks to handle IOException:

try {
    $input = new FileInputStream('nonexistent.txt');
    $input->readLine();
} catch (\Chigi\Component\IO\IOException $e) {
    \Log::error("File read failed: " . $e->getMessage());
}

Gotchas and Tips

Pitfalls

1. PHP Version Compatibility

  • Issue: The package may fail on PHP 8.x due to:
    • Deprecated features (e.g., create_function, magic methods).
    • Strict typing conflicts.
  • Workaround:
    • Use a PHP 7.4 environment for testing.
    • Patch deprecated methods manually (e.g., replace __get() with properties).

2. Lack of Laravel-Specific Features

  • Issue: No integration with:
    • Laravel’s service container (requires manual binding).
    • Facades (e.g., IO::stream()).
    • Events or queues.
  • Workaround:
    • Use service providers to bridge the gap (as shown above).
    • Avoid mixing with Laravel’s native Storage or Filesystem in the same context.

3. Resource Leaks

  • Issue: Streams must be explicitly closed to avoid:
    • File handles remaining open.
    • Memory leaks in custom implementations.
  • Tip:
    • Always call close() in a finally block or use PHP’s __destruct().
    • Example:
      $input = new FileInputStream('file.txt');
      try {
          $data = $input->read();
      } finally {
          $input->close();
      }
      

4. No Async Support

  • Issue: Streams are synchronous only (no ReactPHP or Amp compatibility).
  • Workaround:
    • Use Laravel’s queue system for async file processing.
    • Offload to a separate process (e.g., symfony/process).

5. Limited Error Handling

  • Issue: Custom exceptions (e.g., EOFException) may not integrate with Laravel’s logging.
  • Tip:
    • Catch exceptions and log them via Laravel’s Log facade:
      try {
          $input->readLine();
      } catch (\Chigi\Component\IO\IOException $e) {
          \Log::
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor