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

File Manager Laravel Package

kherge/file-manager

Strict file and stream manager for PHP: safe read/write operations with unified APIs for files, in-memory strings, and existing streams. Supports iteration over contents and consistent handling via File, Memory, and Stream managers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require kherge/file-manager
    

    Add the namespace to your composer.json autoload or use it directly in your code.

  2. First Use Case: Handle a file with strict read/write operations:

    use KHerGe\File\File;
    
    $file = new File('path/to/file.txt', 'r'); // 'r' for read, 'w' for write
    
  3. Key Classes:

    • File: For file operations.
    • Memory: For in-memory string operations.
    • Stream: For stream-based operations (e.g., HTTP responses, database streams).

Implementation Patterns

Core Workflows

  1. File Operations:

    • Reading:
      $file = new File('data.csv', 'r');
      foreach ($file->iterate() as $line) {
          // Process line-by-line (CSV-friendly)
      }
      
    • Writing:
      $file = new File('output.txt', 'w');
      $file->write('Hello, world!');
      
  2. Memory Operations:

    • Treat strings as files:
      $memory = new Memory('Initial content', false);
      $memory->write('Appended text');
      $content = $memory->read();
      
  3. Stream Operations:

    • Useful for HTTP responses or database streams:
      $stream = fopen('php://memory', 'r+');
      $streamManager = new Stream($stream);
      $streamManager->write('Streamed data');
      
  4. CSV Handling:

    • Leverage built-in CSV support:
      $csv = new File('data.csv', 'r');
      foreach ($csv->iterate() as $row) {
          $row = str_getcsv($row); // Parse CSV row
      }
      
  5. Permissions & Metadata:

    • Set/get file permissions and timestamps:
      $file->setPermissions(0644); // Unix permissions
      $file->setLastModified(time());
      
  6. Locking:

    • Prevent concurrent access:
      $file->lock();
      // Critical section
      $file->unlock();
      

Integration Tips

  • Laravel Filesystem: Use with Laravel’s Storage facade for consistency:

    $path = storage_path('app/file.txt');
    $file = new File($path, 'r');
    
  • Service Providers: Bind the package to Laravel’s container for dependency injection:

    $this->app->bind(FileInterface::class, function ($app) {
        return new File($app['path'], 'r');
    });
    
  • Form Requests: Validate file uploads with strict operations:

    public function store(Request $request) {
        $file = new File($request->file('upload')->path(), 'r');
        // Process file...
    }
    

Gotchas and Tips

Pitfalls

  1. Locking Conflicts:

    • Locking streams may fail on non-lockable resources (e.g., php://memory). Test with flock() compatibility:
      if (!$file->lock()) {
          throw new \RuntimeException('Could not acquire lock');
      }
      
  2. CSV Parsing:

    • The iterate() method returns raw lines. Use str_getcsv() or a library like league/csv for robust parsing.
  3. Path Resolution:

    • Symbolic links may cause issues. Use resolve() to dereference them:
      $file = new File('symlink/to/file.txt', 'r');
      $file->resolve(); // Resolves symlinks recursively
      
  4. Permissions:

    • Unix permissions (e.g., 0644) are strict. Ensure your server user has write access to the target directory.
  5. Memory Limits:

    • Memory class loads entire content into RAM. Avoid for large strings (>100MB).

Debugging

  • File Not Found: Use absolute paths or realpath() to debug:

    $file = new File(realpath('relative/path'), 'r');
    
  • Permission Denied: Check storage_path() permissions or run:

    chmod -R 775 storage/
    

Extension Points

  1. Custom Stream Wrappers: Extend Stream for database streams or S3:

    class S3Stream extends Stream {
        public function __construct(Aws\S3\S3Client $client, string $bucket, string $key) {
            $stream = $client->getObject($bucket, $key);
            parent::__construct($stream);
        }
    }
    
  2. Event Hooks: Override methods like write() or read() to log operations:

    class LoggedFile extends File {
        public function write($data) {
            Log::debug("Writing to {$this->path}");
            return parent::write($data);
        }
    }
    
  3. Temporary Files: Use the createTempPath() helper for cleanup:

    $tempPath = File::createTempPath();
    // Use $tempPath...
    unlink($tempPath); // Cleanup
    

Config Quirks

  • No Laravel Config: The package lacks Laravel-specific config. Use environment variables for paths:

    $file = new File(env('UPLOAD_PATH').'/file.txt', 'r');
    
  • Deprecated Methods: Check FileInterface for deprecated methods (e.g., pre-2.0 locking). Use lock()/unlock() instead.

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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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