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

Doze Laravel Package

dbstudios/doze

Doze is a small PHP response helper built on Symfony Serializer/HttpFoundation. Configure a serializer + responder to produce encoded responses (e.g., JSON) and use its field selector/attributes support to return only requested fields in API payloads.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dbstudios/doze
    
  2. Basic Configuration Register the serializer and responder in a service provider (e.g., AppServiceProvider):

    use Symfony\Component\Serializer\Serializer;
    use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
    use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
    use Symfony\Component\Serializer\Encoder\JsonEncoder;
    use Doze\Responder;
    
    public function register()
    {
        $this->app->singleton('serializer', function () {
            return new Serializer([
                new DateTimeNormalizer(),
                new ObjectNormalizer(),
            ], [
                new JsonEncoder(),
            ]);
        });
    
        $this->app->singleton('responder', function ($app) {
            return new Responder($app->make('serializer'));
        });
    }
    
  3. First Use Case Inject the responder into a controller and use it to return JSON responses:

    use Doze\Responder;
    
    public function show(Responder $responder)
    {
        $data = ['name' => 'Example', 'value' => 123];
        return $responder->createResponse('json', $data);
    }
    

Implementation Patterns

Serialization Workflows

  1. Normalizing Data Use ObjectNormalizer for Eloquent models or custom objects:

    $normalizer = new ObjectNormalizer();
    $normalizer->setIgnoredAttributes(['password', 'created_at']); // Ignore sensitive fields
    
  2. Custom Serialization Extend ObjectNormalizer for custom logic:

    use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
    
    class CustomNormalizer implements ContextAwareNormalizerInterface
    {
        public function normalize($object, $format = null, array $context = [])
        {
            return ['custom_key' => $object->getCustomValue()];
        }
        // ... (implement other required methods)
    }
    
  3. Response Handling Chain responders for layered responses:

    $responder->createResponse('json', $data)
        ->withHeader('X-Custom-Header', 'value');
    

Integration with Laravel

  1. Middleware for API Responses Wrap responses globally:

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if ($response instanceof \Symfony\Component\HttpFoundation\Response) {
            $responder = app('responder');
            return $responder->createResponse('json', $response->getData());
        }
        return $response;
    }
    
  2. API Resource Integration Use with Laravel’s JsonResource for consistency:

    $responder->createResponse('json', new JsonResource($model));
    
  3. Error Handling Standardize error responses:

    try {
        // Risky operation
    } catch (\Exception $e) {
        return $responder->createResponse('json', [
            'error' => $e->getMessage(),
            'code' => $e->getCode(),
        ], 400);
    }
    

Gotchas and Tips

Pitfalls

  1. Serializer Configuration

    • Issue: Forgetting to register DateTimeNormalizer may cause DateTime fields to serialize as strings.
    • Fix: Always include DateTimeNormalizer for datetime fields.
  2. Circular References

    • Issue: ObjectNormalizer throws CircularReferenceException for nested objects with bidirectional relationships.
    • Fix: Use setCircularReferenceHandler:
      $normalizer->setCircularReferenceHandler(function ($object) {
          return $object->getId();
      });
      
  3. Deprecated Package

    • Issue: Last release in 2018; may not work with newer Laravel/Symfony versions.
    • Fix: Test thoroughly or fork the package for updates.

Debugging

  1. Inspect Serialized Data Use debug() to verify normalization:

    $normalized = $serializer->normalize($object);
    dd($normalized);
    
  2. Check Encoder Support Ensure the encoder matches the format (e.g., JsonEncoder for 'json').

Extension Points

  1. Custom Responders Extend Doze\Responder for additional formats (e.g., XML):

    class XmlResponder extends Responder
    {
        public function createResponse($format, $data, $status = 200)
        {
            $xml = new \SimpleXMLElement('<root/>');
            array_walk_recursive($data, function($value, $key) use ($xml) {
                $xml->addChild($key, $value);
            });
            return new Response($xml->asXML(), $status, ['Content-Type' => 'application/xml']);
        }
    }
    
  2. Dynamic Normalizers Register normalizers conditionally:

    $normalizers = [new ObjectNormalizer()];
    if (class_exists(\League\Fractal\Manager::class)) {
        $normalizers[] = new FractalNormalizer();
    }
    $serializer = new Serializer($normalizers, [$encoder]);
    
  3. Performance

    • Cache the serializer instance (already done via Laravel’s container).
    • Avoid deep normalization for large datasets; use max_depth in ObjectNormalizer.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware