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.
Installation:
composer require typhoon/exporter
Add to composer.json under require or require-dev depending on your needs.
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);
Where to Look First:
Exporting Data for Serialization:
Use Exporter::export() to generate PHP-compatible strings for:
$response = $this->api->fetchData();
file_put_contents('cache/' . $id . '.php', '<?php return ' . Exporter::export($response) . ';');
$users = User::all();
file_put_contents('database/seeders/UsersSeeder.php', '<?php return ' . Exporter::export($users->toArray()) . ';');
Integration with Laravel:
// 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);
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) . ';');
Exporting Objects with Custom Logic: Extend the exporter for domain-specific types (see Extension Points below).
json_encode() + json_decode() as a fallback:
$exported = Exporter::export($data);
if (str_contains($exported, 'Circular reference')) {
$exported = json_encode($data);
}
json_encode() for better performance.Str::of($exported)->replaceMatches('/[^a-zA-Z0-9_\-\.]/', '')).Variable Name Collisions:
The exporter uses short variable names (e.g., $a, $b) by default. This can cause issues if:
file_put_contents('data.php', '<?php return function() { return ' . Exporter::export($data) . '; }();');
Non-Serializable Objects:
Objects with private properties or custom __toString() may not export correctly.
JsonSerializable or use get_object_vars():
$exported = Exporter::export((array) $object);
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.
json_encode() if trailing commas are required.Resource Intensive Exports: Deeply nested objects/arrays may generate large strings, causing memory issues.
json_encode() with JSON_PRETTY_PRINT.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!');
Log Exported Code: For debugging, log the raw output:
\Log::debug('Exported:', ['code' => Exporter::export($data)]);
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).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.
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
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');
}
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");
Edge Cases:
1.1 + 2.2 becomes 3.3000000000000003). Use json_encode() for precision.$exported = Exporter::export($date->format('Y-m-d H:i:s'));
How can I help you explore Laravel packages today?