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 Directory Laravel Package

spatie/temporary-directory

Create, use, and automatically clean up temporary directories in PHP. Spatie TemporaryDirectory makes it easy to generate a temp folder (in your system temp path), build file paths inside it, and delete everything when you’re done.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Use Case Alignment: The package excels in scenarios requiring ephemeral storage for file processing (e.g., uploads, exports, caching, or testing). It aligns well with Laravel’s file handling needs, particularly for:
    • Temporary file generation (e.g., PDFs, CSV exports, image thumbnails).
    • Isolated environments (e.g., sandboxed processing, background jobs).
    • Testing (e.g., mocking file systems, avoiding clutter in /storage).
  • Laravel Synergy: Integrates seamlessly with Laravel’s filesystem abstractions (e.g., Storage facade) and event-driven workflows (e.g., queues, commands). The deleteWhenDestroyed() feature complements Laravel’s dependency injection and service container lifecycle.

Integration Feasibility

  • Low Friction: Minimal boilerplate—just use Spatie\TemporaryDirectory\TemporaryDirectory and chain methods (e.g., ->create()->path('file.txt')).
  • Customization: Supports:
    • Custom paths (e.g., ->location(storage_path('temp'))).
    • Permissions (e.g., ->permission(0755)).
    • Forceful creation (e.g., ->force()).
  • Laravel-Specific Hooks: Can be extended with Laravel’s service providers, events, or observers to auto-cleanup directories (e.g., on job completion or HTTP request end).

Technical Risk

  • Minimal: The package is battle-tested (PHP 8.1–8.5, 970 stars), with no major breaking changes in 2+ years. Risks are limited to:
    • Race Conditions: Concurrent directory creation (mitigated by timestamped names).
    • Permission Issues: Default 0777 may conflict with shared hosting (solved via permission()).
    • Memory Leaks: deleteWhenDestroyed() relies on PHP’s garbage collection (tested in CI).
  • Dependencies: Only requires PHP ≥8.1 (no Laravel-specific dependencies).

Key Questions

  1. Scope of Use:
    • Will this replace Laravel’s storage_path('app') for all temporary files, or only specific workflows (e.g., exports)?
    • Are there size limits for temporary files (e.g., /tmp quotas on shared hosts)?
  2. Cleanup Strategy:
    • Should cleanup be manual (e.g., via delete()), automatic (deleteWhenDestroyed()), or event-driven (e.g., Laravel’s terminating middleware)?
  3. Cross-Environment Consistency:
    • How will custom paths (e.g., storage_path('temp')) behave across local/dev/prod?
  4. Testing Impact:
    • Will tests need to mock the package, or can real temp dirs be used (e.g., with ->delete() in tearDown)?
  5. Performance:
    • For high-throughput systems (e.g., bulk exports), will directory creation/deletion become a bottleneck?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Filesystem: Works with Laravel’s Storage facade (e.g., Storage::put($tempDir->path('file.txt'), $content)).
    • Queues/Jobs: Ideal for background tasks (e.g., generating reports) where cleanup happens post-execution.
    • Artisan Commands: Useful for CLI tools needing scratch space.
    • Testing: Replaces Storage::fake() for file-based tests (e.g., TemporaryDirectory::make()->path('test.txt')).
  • PHP Extensions:
    • No external dependencies beyond PHP core (e.g., FilesystemIterator for deletion).

Migration Path

  1. Pilot Phase:
    • Start with non-critical workflows (e.g., export features, test environments).
    • Example: Replace hardcoded /tmp paths in a CSV export job:
      // Before
      $tempFile = tempnam(sys_get_temp_dir(), 'export_');
      // After
      $tempDir = TemporaryDirectory::make()->create();
      $tempFile = $tempDir->path('export.csv');
      
  2. Gradual Adoption:
    • Use dependency injection to replace direct filesystem calls:
      public function __construct(private TemporaryDirectory $tempDir) {}
      
    • Leverage Laravel’s service container to bind the package globally:
      $this->app->singleton(TemporaryDirectory::class, fn() => new TemporaryDirectory());
      
  3. Legacy Integration:
    • For existing code using sys_get_temp_dir(), wrap calls in a facade or helper:
      function tempPath(string $filename): string {
          return TemporaryDirectory::make()->create()->path($filename);
      }
      

Compatibility

  • PHP Versions: Supports Laravel’s current LTS (PHP 8.1+).
  • Laravel Versions: No Laravel-specific code; works with all modern versions.
  • Hosting Constraints:
    • Shared Hosting: May need ->location(storage_path('temp')) to avoid /tmp restrictions.
    • Docker/Kubernetes: Ensure container temp dirs (/tmp) have sufficient space.

Sequencing

  1. Phase 1: Replace manual tempnam()/sys_get_temp_dir() calls.
  2. Phase 2: Integrate with queues/jobs for automatic cleanup.
  3. Phase 3: Extend to testing (replace Storage::fake() where applicable).
  4. Phase 4: Optimize for high-scale use (e.g., batch processing).

Operational Impact

Maintenance

  • Pros:
    • No Maintenance Overhead: The package is self-contained (MIT license, no external APIs).
    • Automatic Updates: Composer handles updates; breaking changes are rare (e.g., PHP 8+ only).
  • Cons:
    • Custom Logic: If extending (e.g., adding logging), maintain custom code.
    • Permission Debugging: May require troubleshooting 0777 vs. 0755 issues in prod.

Support

  • Troubleshooting:
    • Common Issues:
      • Directories not deleting: Check for open file handles (use ->empty() first).
      • Path conflicts: Use ->name('unique_prefix') or ->force().
    • Logs: Add debug logs for directory paths/permissions:
      $tempDir->create();
      Log::debug('Temp dir created at:', [$tempDir->getPath()]);
      
  • Vendor Support: Spatie’s postcardware and GitHub issues are responsive.

Scaling

  • Performance:
    • Directory Creation: Minimal overhead (microseconds for mkdir).
    • Deletion: FilesystemIterator ensures robust cleanup (even with symlinks).
    • Concurrency: Timestamped names prevent collisions under load.
  • Resource Usage:
    • Memory: deleteWhenDestroyed() relies on PHP’s garbage collection (tested to ~10K dirs/sec).
    • Disk: Temporary directories are ephemeral; monitor /tmp or custom paths for quotas.
  • Horizontal Scaling: No shared state; safe for distributed systems (e.g., Laravel Horizon).

Failure Modes

Failure Scenario Impact Mitigation
Directory not deleted Disk space exhaustion Use try-catch with delete(); log failures.
Permission denied (0777) Write operations fail Set ->permission(0755) or adjust hosting.
Race condition (same name) Overwritten data Use ->name(uniqid()) or ->force().
PHP garbage collection delay Zombie directories Call unset($tempDir) or ->delete().
Hosting /tmp quota exceeded Job failures Use ->location(storage_path('temp')).

Ramp-Up

  • Onboarding:
    • Documentation: Spatie’s README is comprehensive; add internal examples for Laravel-specific use cases (e.g., queues).
    • Training: Focus on:
      • When to use deleteWhenDestroyed() vs. manual delete().
      • Custom path/permission scenarios.
  • Testing:
    • Unit Tests: Mock TemporaryDirectory to verify cleanup:
      $tempDir = $this->createMock(TemporaryDirectory::class);
      $tempDir->method('delete')->willReturn(true);
      
    • Integration Tests: Test real dir creation/deletion in CI (e.g., ->delete() in tearDown).
  • Rollout:
    • Canary Release: Deploy to a non-critical feature first (e.g., admin
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony