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

Temp File Laravel Package

makasim/temp-file

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require makasim/temp-file
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "Makasim\\File\\": "vendor/makasim/temp-file/src"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Generate a temporary file with default settings:

    use Makasim\File\TempFile;
    
    $tempFile = TempFile::generate();
    echo "Temporary file created at: " . $tempFile->getPathname();
    
  3. Where to Look First:

    • Source Code (minimal, ~100 lines).
    • TempFile.php for core methods (generate(), from(), persist()).
    • SplFileInfo docs (since TempFile extends it).

Implementation Patterns

Core Workflows

  1. Generating Temporary Files:

    // Default: random name in system temp dir
    $file = TempFile::generate();
    
    // Custom path/prefix
    $file = TempFile::generate('/custom/path', 'prefix_');
    
  2. Copying Persisted Files:

    $persistedFile = TempFile::from('/path/to/existing/file.txt');
    // File is now a TempFile but persists until `persist()` or script end.
    
  3. File Operations:

    // Write data
    file_put_contents($file->getPathname(), 'Hello, TempFile!');
    
    // Read data (SplFileInfo methods)
    $content = file_get_contents($file->getPathname());
    
  4. Preventing Auto-Deletion:

    $file = TempFile::generate();
    $file->persist(); // File survives script shutdown
    
  5. Contextual Usage:

    // In a Laravel service:
    public function processUploadedFile(UploadedFile $uploadedFile) {
        $tempFile = TempFile::from($uploadedFile->getPathname());
        // Process $tempFile...
    }
    

Integration Tips

  • Laravel Filesystem: Use with Storage::disk('local')->put() for hybrid temp/persisted storage:

    $tempFile = TempFile::generate();
    Storage::disk('local')->put($tempFile->getFilename(), $tempFile->getContent());
    
  • Testing: Mock TempFile in unit tests to avoid filesystem I/O:

    $mockFile = $this->createMock(SplFileInfo::class);
    $this->app->instance(TempFile::class, $mockFile);
    
  • Cleanup: Manually delete files if needed (though auto-cleanup is default):

    if ($file->exists()) {
        $file->delete();
    }
    

Gotchas and Tips

Pitfalls

  1. Auto-Deletion Timing:

    • Files are only deleted on script shutdown (not immediately).
    • Avoid relying on unlink() or delete() unless persist() is called.
  2. Path Validation:

    • generate() uses sys_get_temp_dir() by default. Ensure the target directory is writable:
      if (!is_writable(sys_get_temp_dir())) {
          throw new RuntimeException('Temp directory not writable');
      }
      
  3. Race Conditions:

    • If multiple scripts generate files with the same name, collisions may occur. Use unique prefixes:
      $file = TempFile::generate(null, 'unique_' . uniqid());
      
  4. Laravel Artisan Commands:

    • Temp files may not clean up if the command exits abruptly (e.g., Artisan::call() without proper shutdown).
  5. Windows Line Endings:

    • Files created on Windows may have \r\n line endings, which can cause issues in cross-platform apps. Normalize if needed:
      $content = str_replace(["\r\n", "\r"], "\n", $content);
      

Debugging

  • Verify File Existence:

    if (!$file->exists()) {
        throw new RuntimeException("Temp file not created at: " . $file->getPathname());
    }
    
  • Check Permissions:

    if (!is_writable(dirname($file->getPathname()))) {
        throw new RuntimeException("Cannot write to temp directory");
    }
    

Extension Points

  1. Custom Storage: Override the temp directory in a child class:

    class CustomTempFile extends TempFile {
        public static function generate($path = null, $prefix = null) {
            return new static(sys_get_temp_dir() . '/custom/', $prefix);
        }
    }
    
  2. Post-Shutdown Hooks: Register a shutdown function to log temp file cleanup:

    register_shutdown_function(function() {
        $tempFiles = TempFile::getAll(); // Hypothetical; not natively supported
        error_log("Cleaned up " . count($tempFiles) . " temp files");
    });
    
  3. Laravel Service Provider: Bind the package to the container for dependency injection:

    $this->app->bind(TempFile::class, function() {
        return TempFile::generate();
    });
    

Config Quirks

  • No Config File: All settings are passed via method arguments (e.g., generate($path, $prefix)).
  • No File Size Limits: Be mindful of system temp dir quotas (e.g., /tmp on Linux).
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
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