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

Files Laravel Package

yiisoft/files

Yii Files is a PHP 8+ utility package with FileHelper methods for common filesystem tasks: ensure/create directories with permissions, remove or clear directories, filter files via path matching, and other file and directory management helpers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require yiisoft/files
    

    No additional configuration is required for basic usage.

  2. First Use Case: Create a file or directory in a Laravel project:

    use Yiisoft\Files\FileHelper;
    
    // Create a directory
    FileHelper::createDirectory('storage/app/uploads');
    
    // Write to a file
    FileHelper::writeFile('storage/app/uploads/test.txt', 'Hello, Yii!');
    
  3. Key Classes:

    • Yiisoft\Files\FileHelper: Core utility class for file/directory operations.
    • Yiisoft\Files\PathHelper: Path manipulation utilities.
    • Yiisoft\Files\Filesystem: Filesystem abstraction (if extended).
  4. Where to Look First:

    • README for basic usage.
    • API Docs for method signatures.
    • Laravel’s storage/ or public/ directories for testing.

Implementation Patterns

Common Workflows

  1. File Operations:

    // Read/write files
    $content = FileHelper::readFile('path/to/file.txt');
    FileHelper::writeFile('path/to/file.txt', $content, FileHelper::WRITE_APPEND);
    
    // Handle file existence
    if (FileHelper::isFile('path/to/file.txt')) {
        FileHelper::deleteFile('path/to/file.txt');
    }
    
  2. Directory Management:

    // Create directories recursively
    FileHelper::createDirectory('storage/app/cache', 0755, true);
    
    // List files/directories
    $files = FileHelper::findFiles('storage/app/uploads', ['*.jpg']);
    $dirs = FileHelper::findDirectories('storage/app/uploads');
    
  3. Path Manipulation:

    // Normalize paths (cross-platform)
    $normalized = PathHelper::normalize('path/with/../duplicates');
    
    // Join paths safely
    $fullPath = PathHelper::concat('storage', 'app', 'uploads');
    
  4. Integration with Laravel:

    • Use storage_path() or public_path() helpers to resolve Laravel-specific paths:
      $laravelPath = storage_path('app/uploads');
      FileHelper::createDirectory($laravelPath);
      
    • Combine with Laravel’s File facade for hybrid usage:
      use Illuminate\Support\Facades\File as LaravelFile;
      
      // YiiSoft for advanced operations, Laravel for simplicity
      LaravelFile::exists($path) ? FileHelper::deleteFile($path) : null;
      
  5. Batch Processing:

    // Process all files in a directory
    foreach (FileHelper::findFiles('storage/app/logs') as $file) {
        if (FileHelper::getFileExtension($file) === 'log') {
            // Process log file
        }
    }
    
  6. Temporary Files:

    $tempDir = FileHelper::createTempDirectory('prefix_');
    FileHelper::writeFile($tempDir . '/temp.txt', 'Temporary data');
    // Cleanup later: FileHelper::deleteDirectory($tempDir);
    

Gotchas and Tips

Pitfalls

  1. Path Separators:

    • Always use PathHelper::normalize() or PathHelper::concat() to avoid cross-platform issues (e.g., path/to/file vs. path\to\file).
    • Gotcha: Hardcoding / or \ in paths will break on Windows/Linux.
  2. Permissions:

    • FileHelper::createDirectory() requires writable parent directories. Use 0755 or 0777 for explicit permissions, but avoid 0777 in production.
    • Debug Tip: Check permissions with FileHelper::isWritable('path').
  3. File Locking:

    • The package doesn’t support file locking natively. Use flock() or Laravel’s Storage facade for concurrent access:
      $file = storage_path('file.lock');
      $handle = fopen($file, 'w');
      flock($handle, LOCK_EX); // Acquire lock
      // Critical section
      flock($handle, LOCK_UN); // Release lock
      fclose($handle);
      
  4. Recursive Operations:

    • FileHelper::deleteDirectory() will not prompt for confirmation. Use cautiously in production:
      FileHelper::deleteDirectory('storage/app/cache', true); // Force delete
      
    • Tip: Test with FileHelper::isDirectoryEmpty() first.
  5. Symbolic Links:

    • FileHelper::isFile() and FileHelper::isDirectory() follow symlinks by default. Use FileHelper::isFileReal() or FileHelper::isDirectoryReal() to check the target.
  6. Memory Usage:

    • Avoid reading large files into memory. Use FileHelper::readFile() with caution for files >100MB. Stream content instead:
      $stream = fopen('large_file.zip', 'r');
      while (!feof($stream)) {
          // Process chunk by chunk
      }
      fclose($stream);
      

Debugging Tips

  1. Verify Paths:
    dd(FileHelper::normalize('path/with/../issues')); // Debug normalized path
    
  2. Check File Existence:
    if (!FileHelper::isFile($path)) {
        throw new \RuntimeException("File not found: {$path}");
    }
    
  3. Log Operations:
    \Log::debug('Creating directory', ['path' => $path, 'permissions' => 0755]);
    FileHelper::createDirectory($path, 0755);
    

Extension Points

  1. Custom Filesystem:

    • Extend Yiisoft\Files\Filesystem to integrate with Laravel’s FilesystemManager:
      use Yiisoft\Files\Filesystem;
      
      class LaravelFilesystem extends Filesystem {
          public function url($path) {
              return asset('storage/' . $path);
          }
      }
      
    • Register in Laravel’s config/filesystems.php:
      'disks' => [
          'yiisoft' => [
              'driver' => 'custom',
              'class' => LaravelFilesystem::class,
          ],
      ],
      
  2. Event Hooks:

    • Listen for file changes using Laravel’s filesystem events (requires additional setup):
      use Illuminate\Filesystem\Events\FileCreated;
      
      event(new FileCreated($path));
      
    • Note: The package itself doesn’t support events natively; wrap calls in Laravel events if needed.
  3. Path Aliases:

    • Create a PathHelper extension for Laravel’s app_path(), config_path(), etc.:
      PathHelper::addAlias('app', app_path());
      $appPath = PathHelper::concat('app', 'Http', 'Controllers');
      
  4. Testing:

    • Use Laravel’s Storage facade to mock filesystem operations in tests:
      Storage::fake('yiisoft');
      FileHelper::writeFile('test.txt', 'data');
      Storage::disk('yiisoft')->assertExists('test.txt');
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport