riimu/kit-phpencoder
Export PHP variables as customizable, readable or compact PHP code. A flexible alternative to var_export() with control over whitespace, array syntax, and useful object conversion—ideal for generated config files and optimized cache output.
Installation
composer require riimu/kit-phpencoder
Add to composer.json if using strict mode:
"require": {
"riimu/kit-phpencoder": "^2.0"
}
Basic Usage
Import the encoder and use it like var_export but with more control:
use Riimu\Kit\PhpEncoder\Encoder;
$encoder = new Encoder();
$output = $encoder->encode([1, 2, 3]);
echo $output; // Outputs: array ( 0 => 1, 1 => 2, 2 => 3, )
First Use Case Generate PHP code for database seeds or fixtures:
$data = ['user_id' => 1, 'name' => 'John Doe'];
$encoder = new Encoder();
$seedCode = $encoder->encode($data);
file_put_contents('database/seeds/UsersTableSeeder.php', "<?php\n\$users = {$seedCode};");
Customizing Output Format
Use EncoderOptions to tweak formatting:
use Riimu\Kit\PhpEncoder\EncoderOptions;
$options = new EncoderOptions();
$options->setArrayFormat(EncoderOptions::ARRAY_FORMAT_SHORT); // array(1, 2, 3)
$encoder = new Encoder($options);
Handling Complex Data
__toArray() or use Encoder::encodeObject().
export type now ensure consistent index order when encoded. For custom objects, explicitly define __toArray() or use Encoder::encodeObject() with a callback.$options->setAllowCircularReferences(false).Integration with Laravel
$this->app->singleton(Encoder::class, function ($app) {
$options = new EncoderOptions();
$options->setArrayFormat(EncoderOptions::ARRAY_FORMAT_SHORT);
return new Encoder($options);
});
Blade::directive('dump', function ($expr) {
return "<?php echo Riimu\\Kit\\PhpEncoder\\Encoder::encode({$expr}); ?>";
});
Batch Processing Encode arrays of data (e.g., for API responses or exports):
$encoder = new Encoder();
$batch = [
['id' => 1, 'name' => 'Foo'],
['id' => 2, 'name' => 'Bar'],
];
$encodedBatch = array_map([$encoder, 'encode'], $batch);
Laravel Eloquent:
Use toArray() or toJson() + json_decode() to flatten models before encoding.
$user = User::find(1);
$encoder->encode($user->toArray());
API Responses:
Replace json_encode() for human-readable debug outputs:
$response = $encoder->encode($apiData);
Log::debug("API Response: {$response}");
Testing: Assert encoded output matches expected PHP syntax:
$this->assertEquals(
"array ( 'key' => 'value', )",
$encoder->encode(['key' => 'value'])
);
PHP 8.2+ Objects:
Ensure consistent index order for objects with export type by implementing __toArray() or using Encoder::encodeObject() with a callback:
$encoder->encodeObject($obj, fn($o) => $o->toArray());
Circular References
CircularReferenceException. Disable with:
$options->setAllowCircularReferences(true);
Encoder::encodeObject() with a custom callback to break cycles.Type Handling
get() or toArray()."function() { ... }"). Use Encoder::encodeCallable() for custom logic.export type now have consistent index order by default.__toArray() or a callback in encodeObject() for predictable behavior.Whitespace Sensitivity
$options->setPrettyPrint(true) for consistency.Performance
Unexpected Output:
Check EncoderOptions settings (e.g., setArrayFormat, setUseShortArraySyntax).
var_dump($encoder->getOptions()->toArray());
Custom Objects:
Implement __toString() or __debugInfo() for fallback encoding.
For PHP 8.2+ objects, ensure __toArray() is defined or use Encoder::encodeObject() with a callback.
Edge Cases: Test with:
null, false, true' in strings)export type behavior.Custom Encoders
Extend Encoder or implement Riimu\Kit\PhpEncoder\EncoderInterface:
class CustomEncoder extends Encoder {
protected function encodeString($value) {
return "/* Custom: */ '{$value}'";
}
}
Filters
Use EncoderOptions::addFilter() to transform values before encoding:
$options->addFilter(function ($value) {
return strtoupper($value);
});
Hooks Override protected methods like:
encodeArray()encodeObject()encodeScalar()Short Array Syntax: Enabled by default in PHP 5.4+. Disable with:
$options->setUseShortArraySyntax(false);
Pretty Printing: Adds newlines/indentation but may break minification:
$options->setPrettyPrint(true);
$options->setIndentString(' ');
PHP 8.2+ Compatibility:
export type now ensure consistent index order during encoding.__toArray() or encodeObject() callbacks.Namespace Handling:
Objects without __toArray() are encoded as stdClass by default. Use Encoder::encodeObject($obj, fn($o) => $o->toArray()) for custom logic.
How can I help you explore Laravel packages today?