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

Filesystem Laravel Package

phar-io/filesystem

phar-io/filesystem is a small PHP utility library from the Phar.io ecosystem that abstracts common filesystem tasks with a clean API. Provides helpers for paths, files, and directories, aiming for safer, testable I/O used by tools like phar-io/phar.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require phar-io/filesystem
    

    No additional configuration is required—this is a lightweight, dependency-free package.

  2. First Use Case: Create a filesystem abstraction for a directory (e.g., storage/app):

    use PharIo\Filesystem\Filesystem;
    
    $fs = new Filesystem('storage/app');
    
    • Key Methods to Start:
      • fileExists($path): Check if a file exists.
      • createFile($path, $content): Write a file.
      • readFile($path): Read a file’s contents.
      • deleteFile($path): Remove a file.
      • listContents($path): List directory contents.
  3. Where to Look First:

    • PharIo\Filesystem Docs (if available).
    • Method signatures in PharIo\Filesystem\Filesystem (no external docs, so IDE autocompletion is critical).
    • Example usage in tests (if the package includes them).

Implementation Patterns

Core Workflows

  1. File Operations:

    • Atomic Writes: Use createFile() with a temporary path, then rename (not natively supported; implement manually).
      $tempPath = tempnam(sys_get_temp_dir(), 'prefix_');
      file_put_contents($tempPath, $content);
      $fs->rename($tempPath, $finalPath);
      
    • Directory Traversal:
      foreach ($fs->listContents('path/to/dir') as $item) {
          if ($item->isFile()) {
              $fs->deleteFile($item->getPathname());
          }
      }
      
  2. Integration with Laravel:

    • Storage Facade Wrapper: Extend Laravel’s Storage facade to delegate to PharIo\Filesystem for specific paths:
      use PharIo\Filesystem\Filesystem;
      
      class PharStorage extends \Illuminate\Filesystem\FilesystemAdapter
      {
          public function __construct()
          {
              $this->filesystem = new Filesystem(storage_path('app/phar'));
          }
      }
      
      Register in config/filesystems.php:
      'disks' => [
          'phar' => [
              'driver' => 'local',
              'root' => storage_path('app/phar'),
              'adapter' => PharStorage::class,
          ],
      ];
      
  3. PHAR-Specific Use Cases:

    • Embedding Filesystems in PHARs: Use PharIo\Filesystem to read/write files inside a PHAR archive:
      $pharFs = new Filesystem('phar://myapp.phar');
      $pharFs->createFile('config/app.php', file_get_contents('config/app.php'));
      
  4. Event-Driven Operations:

    • Pre/Post-Hooks: Manually trigger events (e.g., file.creating) by wrapping methods:
      $fs->createFile($path, $content);
      event(new FileCreated($path));
      

Gotchas and Tips

Pitfalls

  1. No Stream Support:

    • Methods like readFile() load entire files into memory. For large files, use fopen() + fread() directly on the underlying filesystem path.
  2. Path Handling:

    • Relative Paths: All paths are relative to the Filesystem constructor’s root. Use realpath() or dirname(__FILE__) to resolve absolute paths.
    • Trailing Slashes: listContents() fails if $path lacks a trailing slash. Normalize with:
      $fs->listContents(rtrim($path, '/') . '/');
      
  3. Permissions:

    • The underlying filesystem’s permissions apply. Use chmod() or chown() on the root path if needed:
      chmod($fs->getRoot(), 0755);
      
  4. PHAR-Specific Quirks:

    • Write Operations: PHAR archives are read-only by default. Use Phar::webPhar() or Phar::running() to enable writes:
      $phar = new Phar('myapp.phar', FilesystemIterator::CURRENT_AS_FILEINFO | FilesystemIterator::KEY_AS_FILENAME);
      $phar->startBuffering();
      

Debugging Tips

  1. Verify Root Path:

    • Always log the resolved root path to avoid confusion:
      $fs = new Filesystem('storage/app');
      \Log::debug('Filesystem root:', [$fs->getRoot(), realpath($fs->getRoot())]);
      
  2. Check for Silent Failures:

    • Methods like deleteFile() return bool. Add validation:
      if (!$fs->deleteFile($path)) {
          throw new \RuntimeException("Failed to delete {$path}");
      }
      
  3. Test with Temporary Directories:

    • Use sys_get_temp_dir() for testing to avoid polluting your project:
      $tempDir = tempnam(sys_get_temp_dir(), 'test_fs_');
      rmdir($tempDir);
      $fs = new Filesystem($tempDir);
      

Extension Points

  1. Custom Filesystem Adapters:

    • Implement PharIo\Filesystem\FilesystemInterface for S3, FTP, etc.:
      class S3Filesystem implements FilesystemInterface
      {
          public function fileExists($path) {
              return $this->s3->objectExists("bucket/{$path}");
          }
          // ... other methods
      }
      
  2. Event Dispatching:

    • Create a decorator to log or validate operations:
      class LoggingFilesystem implements FilesystemInterface
      {
          private $fs;
      
          public function __construct(Filesystem $fs) {
              $this->fs = $fs;
          }
      
          public function createFile($path, $content) {
              \Log::info("Creating file: {$path}");
              return $this->fs->createFile($path, $content);
          }
      }
      
  3. Laravel Service Provider:

    • Bind the filesystem to the container for dependency injection:
      $this->app->bind(Filesystem::class, function () {
          return new Filesystem(storage_path('app/phar'));
      });
      
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium