Installation
composer require b2pweb/bdf-serializer
No additional configuration is required—just autoload the package.
First Use Case: Serializing/Deserializing Data
use B2PWeb\BDFSerializer\Serializer;
$serializer = new Serializer();
$data = ['name' => 'John', 'age' => 30, 'active' => true];
// Serialize to JSON (default)
$serialized = $serializer->serialize($data);
// Output: '{"name":"John","age":30,"active":true}'
// Deserialize back to PHP
$deserialized = $serializer->deserialize($serialized);
// Output: ['name' => 'John', 'age' => 30, 'active' => true]
Where to Look First
B2PWeb\BDFSerializer\Serializer.README.md for basic examples and edge cases.$serializer = new Serializer();
$serialized = $serializer->serialize($data); // JSON by default
$deserialized = $serializer->deserialize($serialized);
Override the Serializer class to add support for XML, YAML, etc.:
use B2PWeb\BDFSerializer\Serializer as BaseSerializer;
class CustomSerializer extends BaseSerializer {
public function serialize($data, string $format = 'json'): string {
if ($format === 'xml') {
return $this->toXml($data); // Implement custom logic
}
return parent::serialize($data, $format);
}
}
Bind the serializer in AppServiceProvider for dependency injection:
public function register() {
$this->app->singleton(Serializer::class, function ($app) {
return new Serializer();
});
}
use B2PWeb\BDFSerializer\Serializer;
public function store(Request $request, Serializer $serializer) {
$validated = $request->validate([...]);
$serializedData = $serializer->serialize($validated);
// Store $serializedData in DB or cache
}
The serializer supports objects if they implement JsonSerializable or have a toArray() method:
class User implements JsonSerializable {
public function jsonSerialize() {
return ['name' => $this->name, 'email' => $this->email];
}
}
$user = new User();
$serialized = $serializer->serialize($user); // Works!
Automatically converts to ISO-8601 strings:
$data = ['created_at' => new DateTime()];
$serialized = $serializer->serialize($data);
// Output: '{"created_at":"2023-10-01T12:00:00+00:00"}'
Wrap serialization in try-catch blocks:
try {
$serialized = $serializer->serialize($data);
} catch (\Exception $e) {
Log::error("Serialization failed: " . $e->getMessage());
return response()->json(['error' => 'Invalid data'], 400);
}
Circular References
The serializer does not handle circular references (e.g., self-referencing objects). Use json_encode() with JSON_THROW_ON_ERROR or a library like spatie/array-to-object for such cases.
Non-Serializable Types
Illuminate\Http\Resources\Json\JsonResource won’t serialize by default. Use ->toArray() or ->resolve() first.Whitespace/Pretty-Printing The default JSON output is minified. For pretty-printing:
$serialized = $serializer->serialize($data, JSON_PRETTY_PRINT);
Check Input Data Always validate data before serialization:
if (!is_array($data) && !$data instanceof JsonSerializable) {
throw new \InvalidArgumentException("Data must be array or JsonSerializable");
}
Log Serialized Output Use Laravel’s logging to inspect serialized strings:
\Log::debug("Serialized data:", ['data' => $serialized]);
Test Edge Cases Test with:
Custom Encoders/Decoders
Extend the Serializer class to add format support (e.g., Protocol Buffers):
class ProtobufSerializer extends BaseSerializer {
public function serialize($data, string $format = 'json'): string {
if ($format === 'protobuf') {
return $this->encodeProtobuf($data);
}
return parent::serialize($data, $format);
}
}
Hooks for Pre/Post Processing
Override serialize() and deserialize() to add logic:
class HookedSerializer extends BaseSerializer {
public function serialize($data): string {
$data = $this->preSerialize($data); // Add sensitive data redaction
return parent::serialize($data);
}
}
Configuration While the package has no built-in config, you can inject settings via constructor:
class ConfigurableSerializer extends BaseSerializer {
public function __construct(private array $options = []) {
$this->options = $options;
}
public function serialize($data): string {
$flags = $this->options['json_flags'] ?? 0;
return json_encode($data, $flags);
}
}
foreach ($largeData as $chunk) {
Serializer::dispatch($chunk)->delay(now()->addMinutes(1))->onQueue('serialization');
}
How can I help you explore Laravel packages today?