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

Temporary Filesystem Laravel Package

neutron/temporary-filesystem

TemporaryFilesystem provides a simple PHP API to create temporary directories and files using Symfony’s Filesystem component. Generate single or multiple empty temp files with custom prefixes, suffixes, and extensions—handy for concurrent processes and libraries relying on file extensions.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require neutron/temporary-filesystem
    

    No additional configuration is required—just autoload the package.

  2. First Usage:

    use Neutron\TemporaryFilesystem\TemporaryFilesystem;
    
    $fs = TemporaryFilesystem::create();
    

    This initializes a temporary filesystem backed by Symfony’s Filesystem component.

  3. First Use Case: Create a temporary directory for processing uploads or generating assets:

    $tempDir = $fs->createTemporaryDirectory();
    // Use $tempDir for operations (e.g., `Storage::put($tempDir.'/file.txt', ...)`)
    // Filesystem auto-cleans up on script exit (or manually via `$fs->delete()`).
    

Implementation Patterns

Core Workflows

  1. Temporary File Handling:

    • Single Files:
      $tempFile = $fs->createTemporaryFile('prefix_', '.suffix', 'ext');
      // Example: $tempFile = '/tmp/tmp_abc123_prefix_.ext'
      
    • Bulk Files:
      $tempFiles = $fs->createTemporaryFiles(10, 'thumb_', '.jpg');
      // Useful for batch processing (e.g., image thumbnails).
      
  2. Directory-Based Operations:

    • Scoped Work:
      $dir = $fs->createTemporaryDirectory(0755);
      try {
          // Perform operations in $dir (e.g., `File::put($dir.'/file.txt', ...)`).
      } finally {
          $fs->delete($dir); // Force cleanup (optional).
      }
      
    • Nested Structures: Combine with Storage facade or Symfony\Component\Filesystem\Filesystem for recursive operations.
  3. Integration with Laravel:

    • Storage Facade:
      use Illuminate\Support\Facades\Storage;
      
      $tempPath = $fs->createTemporaryFile();
      Storage::put($tempPath, file_get_contents('original_file'));
      
    • Artisan Commands/Jobs: Use for temporary asset generation (e.g., PDFs, images) during CLI tasks.
  4. Cleanup Strategies:

    • Automatic: Files/dirs are deleted when the $fs instance is garbage-collected.
    • Manual: Call $fs->delete($path) for explicit cleanup (e.g., in finally blocks).

Advanced Patterns

  1. Custom Temporary Path: Override the default temp directory (e.g., for testing):

    $fs = TemporaryFilesystem::create(sys_get_temp_dir().'/custom_temp');
    
  2. Context Managers: Encapsulate usage in a trait or helper:

    trait UsesTempFiles {
        protected function withTempFile(callable $callback) {
            $fs = TemporaryFilesystem::create();
            $file = $fs->createTemporaryFile();
            try {
                return $callback($file);
            } finally {
                $fs->delete($file);
            }
        }
    }
    
  3. Symfony Filesystem Integration: Extend functionality using Symfony’s Filesystem methods:

    $fs->mirror($sourceDir, $fs->createTemporaryDirectory());
    

Gotchas and Tips

Pitfalls

  1. Memory Leaks:

    • Issue: Forgetting to manually delete files/dirs if using long-lived objects (e.g., services).
    • Fix: Use dependency injection for $fs and ensure cleanup in destroy() or finally blocks.
  2. Permissions:

    • Issue: Files/dirs may fail to create if the temp directory lacks write permissions.
    • Fix: Set explicit permissions (e.g., 0755) or verify sys_get_temp_dir() permissions.
  3. Path Portability:

    • Issue: Generated paths are system-specific (e.g., /tmp/ on Linux).
    • Fix: Use relative paths or normalize with realpath() if sharing across environments.
  4. Race Conditions:

    • Issue: Concurrent processes may conflict when creating files with the same prefix.
    • Fix: Use unique prefixes (e.g., uniqid().'_prefix_').

Debugging

  • Verify Cleanup:
    if (!$fs->exists($path)) {
        // Debug: Check if file was deleted.
    }
    
  • Inspect Temp Path:
    $fs->getTempDir(); // Returns the root temp directory.
    

Extension Points

  1. Custom Naming: Override the random string generator:

    $fs->setRandomStringGenerator(fn() => uniqid());
    
  2. Event Hooks: Extend the class to add pre/post-cleanup hooks:

    class HookedTemporaryFilesystem extends TemporaryFilesystem {
        public function delete($path) {
            Log::debug("Deleting: $path");
            parent::delete($path);
        }
    }
    
  3. Storage Backend: For non-disk storage (e.g., S3), wrap the filesystem:

    $fs = new TemporaryFilesystem(new S3FilesystemAdapter());
    

Performance Tips

  • Bulk Operations: Prefer createTemporaryFiles() over looping createTemporaryFile().
  • Avoid Re-creation: Reuse the same $fs instance for multiple operations in a request/job.

Laravel-Specific

  • Testing:
    $fs = TemporaryFilesystem::create(storage_path('tests_temp'));
    // Useful for isolated test environments.
    
  • Queue Jobs: Ensure cleanup in job’s handle() or use a finally block in the job class.
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