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

Cbor Php Laravel Package

spomky-labs/cbor-php

RFC 8949 CBOR encoder/decoder for PHP 8+. Supports all major types, tags, indefinite-length items, and streaming decode for low memory. Type-safe API with normalization to native PHP types; extensible custom tags.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strong Fit for Binary Data Workloads: CBOR’s compact binary format is ideal for Laravel applications handling IoT telemetry, WebAuthn assertions, or COSE tokens where payload size and parsing efficiency are critical. The package’s streaming decoder aligns with Laravel’s queue workers (e.g., Illuminate\Queue) for processing large CBOR payloads without memory overload.
  • Type Safety and Normalization: The library’s type-safe API and .normalize() method bridge CBOR objects to native PHP types (arrays/scalars), reducing friction when integrating with Laravel’s Eloquent models or API responses. Example:
    $cborData = $decoder->decode($request->getContent())->normalize();
    $model->fill($cborData)->save();
    
  • Extensibility for Custom Domains: The tag system enables domain-specific extensions (e.g., healthcare FHIR tags or financial transaction codes) without modifying core logic, leveraging Laravel’s service container for tag registries:
    $app->bind(CustomTagInterface::class, CustomHealthcareTag::class);
    
  • Compatibility with Laravel’s Serialization: Works seamlessly with Laravel’s HTTP message bodies, cache drivers (e.g., Redis), and queue payloads. For example, storing CBOR-encoded data in Redis:
    Redis::set('cbor_key', (string) $cborObject);
    

Integration Feasibility

  • Minimal Laravel-Specific Overhead: The package requires PHP 8.0+, ext-mbstring, and brick/math (optional for large integers). Laravel’s default PHP stack (8.1+) already includes these, reducing setup friction.
  • Dependency Conflicts: Low risk—brick/math is a lightweight dependency with no known conflicts with Laravel’s core or popular packages (e.g., symfony/http-foundation).
  • Testing Integration: The package’s comprehensive test suite and PHPStan integration align with Laravel’s testing practices (PestPHP/PHPUnit). Example test case:
    public function test_cbor_webauthn_assertion()
    {
        $cborAuthenticatorData = AuthenticatorDataTag::create(...);
        $this->assertEquals(
            $expectedBinary,
            (string) $cborAuthenticatorData
        );
    }
    

Technical Risk

Risk Area Mitigation Strategy
Performance Overhead Benchmark against JSON (json_encode/json_decode) in Laravel’s AppServiceProvider boot method. CBOR should outperform JSON for structured data >500B.
Streaming Decoder Test with Laravel’s queue workers (e.g., Illuminate\Queue\Worker) to validate memory efficiency for large payloads (e.g., 10MB+ CBOR blobs).
Tag System Complexity Document custom tag registration in Laravel’s service provider and provide a base tag trait for consistency. Example:
class HealthcareTag extends Tag implements Normalizable
{
    use CBOR\Tag\NormalizableTrait;
}

| Backward Compatibility | Monitor brick/math updates (e.g., v0.15+) via Laravel’s composer.json conflict rules. | | Error Handling | Wrap decoder calls in Laravel’s try-catch blocks and log errors via Log::error() for debugging. Example:

try {
    $decoded = $decoder->decode($request->getContent());
} catch (CBOR\Exception\DecodeException $e) {
    Log::error("CBOR decode failed: {$e->getMessage()}");
    abort(400);
}

Key Questions

  1. Payload Size vs. Complexity Tradeoff:

    • Question: For your use case (e.g., IoT telemetry), does CBOR’s 20–50% size reduction justify the added complexity vs. JSON?
    • Laravel-Specific: Will you need to transcode between CBOR and JSON for API responses? If so, benchmark normalize() + json_encode() vs. direct JSON serialization.
  2. Streaming Requirements:

    • Question: Do you process CBOR payloads >1MB? If yes, validate the streaming decoder’s performance in Laravel’s queue workers or event listeners.
  3. Custom Tag Needs:

    • Question: Will you extend CBOR with domain-specific tags? If so, design a Laravel service provider to register tags globally:
      $app->bind(CustomTagInterface::class, function ($app) {
          return new CustomTag($app['config']['cbor.tags']);
      });
      
  4. WebAuthn/COSE Integration:

    • Question: Are you using CBOR for WebAuthn assertions or COSE tokens? If yes, validate compatibility with Laravel’s webauthn/webauthn package or paragonie/cose.
  5. Cache Storage:

    • Question: Will you store CBOR-encoded data in Laravel’s cache (Redis, file, etc.)? Test serialization/deserialization round-trip times:
      $cached = Cache::get('cbor_key', fn() => (string) $cborObject);
      $decoded = $decoder->decode($cached);
      

Integration Approach

Stack Fit

  • PHP 8.0+: Native support for named arguments, union types, and attributes simplifies CBOR object construction (e.g., MapObject::create([...])).
  • Laravel Ecosystem:
    • HTTP Layer: Integrate with Illuminate\Http\Request/Response for CBOR-encoded API payloads.
    • Queue Workers: Use the streaming decoder for processing large CBOR blobs in background jobs.
    • Cache Drivers: Store CBOR data in Redis/Memcached for low-latency access.
    • Database: Use CBOR for binary columns (e.g., PostgreSQL bytea) to reduce storage costs.
  • Dependencies:
    • Required: ext-mbstring (enabled by default in Laravel’s PHP-FPM).
    • Optional: ext-gmp/ext-bcmath for large integer/decimal performance (enable via php.ini or Laravel Forge).

Migration Path

Phase Action Laravel-Specific Example
Evaluation Benchmark CBOR vs. JSON for your payloads using Laravel’s Benchmark facade or spatie/laravel-benchmark. ```php
use Spatie\Benchmark\Benchmark;
Benchmark::run('CBOR vs JSON', function () {
  $cborTime = Benchmark::run('CBOR', fn() => $decoder->decode($cborData));
  $jsonTime = Benchmark::run('JSON', fn() => json_decode($jsonData, true));

});

| **Pilot Integration** | Start with a **single endpoint** (e.g., `/api/telemetry`) to accept/reject CBOR payloads. Use middleware to validate CBOR content type:                                                                 | ```php
// app/Http/Middleware/ValidateCborContentType.php
public function handle(Request $request, Closure $next) {
    if ($request->isCbor()) { // Custom helper
        $decoder = Decoder::create();
        $request->merge(['cbor' => $decoder->decode($request->getContent())]);
    }
    return $next($request);
}
```                                                                                                                                                                 |
| **Core Integration** | Extend Laravel’s **request/response cycle** to support CBOR:
- Add `isCbor()` helper to `Illuminate\Support\Facades\Request`.
- Create a `CborResponse` macro for `Illuminate\Support\Facades\Response`.
- Register CBOR tags in a **service provider**.                                                                                                                                 | ```php
// app/Providers/CborServiceProvider.php
public function register() {
    $this->app->bind(CustomTagInterface::class, CustomTag::class);
}
```                                                                                                                                                                 |
| **Full Adoption**   | Replace JSON serialization for:
- **Queue payloads** (e.g., `dispatch(new Job($cborPayload))`).
- **Cache storage** (e.g., `Cache::put('key', (string) $cborObject)`).
- **Database binary fields** (e.g., `->binary()` in Eloquent).                                                                                                                           | ```php
// Store CBOR in database
$model->cbor_data = (string) $cborObject;
$model->save();
```                                                                                                                                                                 |

### **Compatibility**
- **Laravel 10+**: Full compatibility due to PHP 8.1+ support.
- **Laravel 9.x**: Works but may require **shims** for PHP 8.0 features (e.g., union types). Test with
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope