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

Bdf Serializer Laravel Package

b2pweb/bdf-serializer

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require b2pweb/bdf-serializer
    

    No additional configuration is required—just autoload the package.

  2. 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]
    
  3. Where to Look First

    • Serializer Class: Core functionality resides in B2PWeb\BDFSerializer\Serializer.
    • Supported Formats: Defaults to JSON but can be extended (see Implementation Patterns).
    • Documentation: Check the README.md for basic examples and edge cases.

Implementation Patterns

1. Basic Serialization Workflows

JSON (Default)

$serializer = new Serializer();
$serialized = $serializer->serialize($data); // JSON by default
$deserialized = $serializer->deserialize($serialized);

Custom Formats (Extending Support)

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);
    }
}

2. Laravel Integration

Service Provider Binding

Bind the serializer in AppServiceProvider for dependency injection:

public function register() {
    $this->app->singleton(Serializer::class, function ($app) {
        return new Serializer();
    });
}

Usage in Controllers/Jobs

use B2PWeb\BDFSerializer\Serializer;

public function store(Request $request, Serializer $serializer) {
    $validated = $request->validate([...]);
    $serializedData = $serializer->serialize($validated);
    // Store $serializedData in DB or cache
}

3. Handling Complex Data Types

Objects

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!

DateTime/DateTimeImmutable

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"}'

4. Error Handling

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);
}

Gotchas and Tips

Pitfalls

  1. 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.

  2. Non-Serializable Types

    • Resources: Laravel’s Illuminate\Http\Resources\Json\JsonResource won’t serialize by default. Use ->toArray() or ->resolve() first.
    • Closures/Generators: These will throw exceptions. Filter them out before serialization.
  3. Whitespace/Pretty-Printing The default JSON output is minified. For pretty-printing:

    $serialized = $serializer->serialize($data, JSON_PRETTY_PRINT);
    

Debugging Tips

  1. Check Input Data Always validate data before serialization:

    if (!is_array($data) && !$data instanceof JsonSerializable) {
        throw new \InvalidArgumentException("Data must be array or JsonSerializable");
    }
    
  2. Log Serialized Output Use Laravel’s logging to inspect serialized strings:

    \Log::debug("Serialized data:", ['data' => $serialized]);
    
  3. Test Edge Cases Test with:

    • Empty arrays/objects.
    • Null values.
    • Nested structures.
    • Special characters (e.g., Unicode, HTML entities).

Extension Points

  1. 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);
        }
    }
    
  2. 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);
        }
    }
    
  3. 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);
        }
    }
    

Performance Considerations

  • Avoid Repeated Serialization: Cache serialized data if reused (e.g., Redis).
  • Batch Processing: For large datasets, use chunking or queue jobs:
    foreach ($largeData as $chunk) {
        Serializer::dispatch($chunk)->delay(now()->addMinutes(1))->onQueue('serialization');
    }
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky