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

Exporter Laravel Package

typhoon/exporter

Typhoon Exporter converts PHP values into valid PHP code strings you can save and later require to recreate the original value. Use Exporter::export($value) to generate code for config, fixtures, caching, or code generation workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require typhoon/exporter
    

    Add to composer.json under require or require-dev depending on your needs.

  2. First Use Case: Export a variable (e.g., array, object, or scalar) to a PHP-compatible string:

    use Typhoon\Exporter\Exporter;
    
    $data = ['name' => 'John', 'age' => 30, 'active' => true];
    $exported = Exporter::export($data);
    file_put_contents('exported_data.php', '<?php return ' . $exported . ';');
    

    Verify by requiring the file:

    $restored = require 'exported_data.php';
    assert($restored === $data);
    
  3. Where to Look First:

    • README.md for basic usage.
    • Tests for edge cases and examples.
    • Release Notes for breaking changes (e.g., variable name optimizations in 0.2.1).

Implementation Patterns

Core Workflows

  1. Exporting Data for Serialization: Use Exporter::export() to generate PHP-compatible strings for:

    • API Responses: Cache or log complex responses.
      $response = $this->api->fetchData();
      file_put_contents('cache/' . $id . '.php', '<?php return ' . Exporter::export($response) . ';');
      
    • Seeding/Testing: Export Eloquent models or collections to seeders.
      $users = User::all();
      file_put_contents('database/seeders/UsersSeeder.php', '<?php return ' . Exporter::export($users->toArray()) . ';');
      
  2. Integration with Laravel:

    • Service Providers: Register a helper for global export:
      // app/Providers/AppServiceProvider.php
      use Typhoon\Exporter\Exporter;
      
      public function boot()
      {
          if ($this->app->environment('local')) {
              $this->app->singleton('export', function () {
                  return new class {
                      public function __invoke($data) {
                          return Exporter::export($data);
                      }
                  };
              });
          }
      }
      
      Usage:
      $exported = app('export')($model);
      
  3. Dynamic File Generation: Combine with Laravel’s Storage facade for cloud-based exports:

    use Illuminate\Support\Facades\Storage;
    
    Storage::put('exports/' . $filename . '.php', '<?php return ' . Exporter::export($data) . ';');
    
  4. Exporting Objects with Custom Logic: Extend the exporter for domain-specific types (see Extension Points below).


Integration Tips

  • Avoid Circular References: The exporter handles simple objects but may fail on circular references. Use json_encode() + json_decode() as a fallback:
    $exported = Exporter::export($data);
    if (str_contains($exported, 'Circular reference')) {
        $exported = json_encode($data);
    }
    
  • Performance: For large datasets, export in chunks or use json_encode() for better performance.
  • Security: Sanitize exported files if generating user-uploaded code (e.g., via Str::of($exported)->replaceMatches('/[^a-zA-Z0-9_\-\.]/', '')).

Gotchas and Tips

Pitfalls

  1. Variable Name Collisions: The exporter uses short variable names (e.g., $a, $b) by default. This can cause issues if:

    • The exported code is included in a scope with pre-existing variables.
    • Fix: Use unique prefixes or wrap exports in anonymous functions:
      file_put_contents('data.php', '<?php return function() { return ' . Exporter::export($data) . '; }();');
      
  2. Non-Serializable Objects: Objects with private properties or custom __toString() may not export correctly.

    • Fix: Implement JsonSerializable or use get_object_vars():
      $exported = Exporter::export((array) $object);
      
  3. Trailing Commas: Version 0.2.1+ removes trailing commas in arrays (e.g., [1, 2, 3] instead of [1, 2, 3,]). This may break existing code expecting trailing commas.

    • Fix: Use json_encode() if trailing commas are required.
  4. Resource Intensive Exports: Deeply nested objects/arrays may generate large strings, causing memory issues.

    • Fix: Limit depth or use json_encode() with JSON_PRETTY_PRINT.

Debugging

  1. Check Output Validity: Validate exports by requiring the generated file:

    $exported = Exporter::export($data);
    file_put_contents('temp.php', '<?php return ' . $exported . ';');
    $restored = require 'temp.php';
    assert($restored === $data, 'Export failed!');
    
  2. Log Exported Code: For debugging, log the raw output:

    \Log::debug('Exported:', ['code' => Exporter::export($data)]);
    
  3. Common Errors:

    • Undefined variable: Ensure all referenced variables are exported (e.g., closures may fail).
    • Parse error: Check for syntax issues (e.g., unclosed braces or invalid PHP constructs).

Tips

  1. Extension Points: Extend the exporter for custom types by implementing Typhoon\Exporter\ExporterInterface:

    use Typhoon\Exporter\ExporterInterface;
    
    class CustomExporter implements ExporterInterface {
        public function export($value): string {
            if ($value instanceof CustomModel) {
                return 'new CustomModel([' . Exporter::export($value->toArray()) . '])';
            }
            return Exporter::export($value);
        }
    }
    

    Register it via the exporter’s setExporter() method (if available) or wrap calls.

  2. Configuration: The exporter has no public config, but you can monkey-patch it for global changes:

    // Override variable naming (e.g., use longer names)
    $reflection = new \ReflectionClass(\Typhoon\Exporter\Exporter::class);
    $property = $reflection->getProperty('variableNames');
    $property->setAccessible(true);
    $property->setValue(null, ['data' => 'data', 'config' => 'config']); // Custom names
    
  3. Testing: Use the exporter in PHPUnit tests to generate test data:

    public function testExport()
    {
        $data = ['key' => 'value'];
        $exported = Exporter::export($data);
        $this->assertSame($data, require 'data.php');
    }
    
  4. Performance Benchmarking: Compare Exporter::export() vs. json_encode() + json_decode() for large datasets:

    $data = range(1, 10000);
    $time = microtime(true);
    $exported = Exporter::export($data);
    $time = microtime(true) - $time;
    \Log::info("Exporter time: {$time}s");
    
  5. Edge Cases:

    • Floats: May lose precision (e.g., 1.1 + 2.2 becomes 3.3000000000000003). Use json_encode() for precision.
    • Dates: Export as strings or timestamps to avoid timezone issues:
      $exported = Exporter::export($date->format('Y-m-d H:i:s'));
      
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony