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

Codec Laravel Package

hyperf/codec

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require hyperf/codec
    

    Note: Since this is a Hyperf package, install it in a Laravel project only if extracting core logic (see [Implementation Patterns]).

  2. First Use Case: Base64 Encoding

    use Hyperf\Codec\Codec;
    
    // Standard Base64
    $encoded = Codec::base64Encode('Laravel');
    echo $encoded; // Outputs: "TGFyYWxlciA="
    
    // URL-safe Base64 (replaces '+', '/', '=')
    $urlSafe = Codec::urlSafeBase64Encode('Laravel');
    echo $urlSafe; // Outputs: "TGFyYWxlciA"
    
  3. First Use Case: Hex Encoding

    $hex = Codec::hexEncode('Laravel');
    echo $hex; // Outputs: "4C61726176656C"
    
  4. Where to Look First


Implementation Patterns

1. Laravel Integration Workflow

Option A: Extract Core Logic (Recommended)

  1. Clone and Strip Hyperf Dependencies

    • Copy src/Codec.php to app/Services/Codec.php.
    • Remove Hyperf-specific imports (e.g., hyperf/di).
    • Update namespace to App\Services\Codec.
  2. Register as a Laravel Service

    // app/Providers/AppServiceProvider.php
    public function register()
    {
        $this->app->singleton(\App\Services\Codec::class, function () {
            return new \App\Services\Codec();
        });
    }
    
  3. Create a Facade (Optional)

    // app/Facades/Codec.php
    namespace App\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class Codec extends Facade
    {
        protected static function getFacadeAccessor()
        {
            return 'codec';
        }
    }
    

    Register the facade in config/app.php:

    'aliases' => [
        // ...
        'Codec' => App\Facades\Codec::class,
    ],
    
  4. Usage in Controllers/Jobs

    use App\Facades\Codec;
    
    $encoded = Codec::base64Encode('Laravel');
    $decoded = Codec::base64Decode($encoded);
    

Option B: Composer Autoload (Quick Start)

If you only need specific methods (e.g., base64Encode), manually include the class:

require_once __DIR__ . '/vendor/hyperf/codec/src/Codec.php';
use Hyperf\Codec\Codec;

$encoded = Codec::base64Encode('Laravel');

2. Common Use Cases

A. API Payload Optimization

  • Problem: JSON payloads are verbose for high-frequency APIs.
  • Solution: Use urlSafeBase64Encode for compact payloads.
$payload = json_encode(['user_id' => 123, 'data' => 'sensitive']);
$compact = Codec::urlSafeBase64Encode($payload);
// Store/transmit $compact instead of JSON.

B. File/Upload Processing

  • Problem: Binary file data needs encoding for storage/transmission.
  • Solution: Encode binary data as hex or base64.
$binaryData = file_get_contents('large_file.bin');
$hexData = Codec::hexEncode($binaryData);
// Store $hexData in a text-based system (e.g., database, cache).

C. URL Parameters

  • Problem: Base64 URLs contain +// which break HTTP.
  • Solution: Use urlSafeBase64Encode.
$token = Codec::urlSafeBase64Encode('auth_token_123');
$url = "https://example.com/api?token=$token";

D. Cryptographic Operations

  • Problem: Need to encode binary keys or hashes.
  • Solution: Use hexEncode for readability.
$hash = hash('sha256', 'secret');
$hexHash = Codec::hexEncode($hash);

3. Advanced Patterns

A. Custom Encoders

Extend Codec to add new encoding schemes:

// app/Services/CustomCodec.php
namespace App\Services;

use Hyperf\Codec\Codec as BaseCodec;

class CustomCodec extends BaseCodec
{
    public static function base32Encode(string $data): string
    {
        // Implement Base32 logic or use a library like `ramsey/base32`.
    }
}

B. Async Processing (Laravel + Swoole)

If using Laravel with Swoole, leverage coroutine-friendly encoding:

use Swoole\Coroutine;
use Hyperf\Codec\Codec;

Coroutine::create(function () {
    $encoded = Codec::base64Encode('async_data');
    // Process $encoded in a coroutine.
});

C. Middleware for Automatic Encoding

Encode/decode request/response bodies:

// app/Http/Middleware/EncodePayload.php
public function handle($request, Closure $next)
{
    $response = $next($request);
    if ($response->getContent()) {
        $encoded = Codec::urlSafeBase64Encode($response->getContent());
        $response->setContent($encoded);
    }
    return $response;
}

Gotchas and Tips

Pitfalls

  1. Hyperf Dependencies

    • Issue: The package uses hyperf/di and hyperf/context, which won’t work in Laravel.
    • Fix: Extract only Codec.php and avoid Hyperf-specific classes.
  2. URL-Safe Base64 Quirks

    • Issue: urlSafeBase64Encode replaces +, /, and = with -, _, and omits padding.
    • Fix: Use Codec::urlSafeBase64Decode to reverse it.
    • Example:
      $encoded = Codec::urlSafeBase64Encode('Laravel='); // "TGFyYWxlciA"
      $decoded = Codec::urlSafeBase64Decode($encoded);   // "Laravel="
      
  3. Binary Data Handling

    • Issue: Passing non-string data (e.g., int, array) to encoders will throw errors.
    • Fix: Cast input to string:
      $encoded = Codec::base64Encode((string) 123); // "MTIz"
      
  4. Performance Overhead

    • Issue: For small payloads, native PHP functions (base64_encode) may be faster.
    • Fix: Benchmark with microtime() before adopting:
      $start = microtime(true);
      Codec::base64Encode(str_repeat('a', 1000));
      $time = microtime(true) - $start;
      echo "Time: $time seconds";
      
  5. No Built-in Decoding for URL-Safe Base64

    • Issue: base64_decode won’t work on URL-safe strings.
    • Fix: Always use Codec::urlSafeBase64Decode.

Debugging Tips

  1. Invalid Input

    • Symptom: TypeError or InvalidArgumentException.
    • Debug:
      try {
          Codec::base64Encode($data);
      } catch (\Throwable $e) {
          dd($data, gettype($data)); // Check input type.
      }
      
  2. Corrupted Data

    • Symptom: Decoded output doesn’t match original.
    • Debug: Compare lengths and content:
      $original = 'Laravel';
      $encoded = Codec::base64Encode($original);
      $decoded = Codec::base64Decode($encoded);
      var_dump($original === $decoded); // Should be true.
      
  3. Memory Issues

    • Symptom: High memory usage with large payloads.
    • Fix: Process data in chunks:
      $chunkSize = 10
      
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.
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
spatie/mailcoach-vapor