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

Json Response Bundle Laravel Package

bu/json-response-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require bu/json-response-bundle dev-master
    

    Add to AppKernel.php:

    new Bu\JsonResponseBundle\BuJsonResponseBundle(),
    
  2. Enable PHP Templating: Update config.yml:

    framework:
        templating:
            engines: ['twig', 'php']
    
  3. First Use Case: Create a PHP template (e.g., src/Application/MyBundle/Resources/views/Product/list.json.php):

    <?php
    return [
        'products' => $products,
        'count' => count($products),
        'meta' => ['timestamp' => time()]
    ];
    

    Annotate your controller:

    use Bu\JsonResponseBundle\Configuration\JsonResponseTemplate;
    
    class ProductController extends Controller
    {
        /**
         * @JsonResponseTemplate("Product/list")
         */
        public function listAction()
        {
            $products = $this->getDoctrine()->getRepository('ApplicationMyBundle:Product')->findAll();
            return $products; // Data passed to template
        }
    }
    

Implementation Patterns

Usage Patterns

  1. Template Inheritance: Use PHP templates to modularize JSON responses. Example:

    // Base template (src/Application/MyBundle/Resources/views/Base/base.json.php)
    <?php return ['@base' => $data]; ?>
    
    // Child template (src/Application/MyBundle/Resources/views/Product/list.json.php)
    <?php
    $baseData = include __DIR__.'/../../Base/base.json.php';
    return array_merge($baseData, [
        'products' => $products
    ]);
    
  2. Dynamic Template Selection: Pass template names dynamically via annotation:

    /**
     * @JsonResponseTemplate("%template%", options={"template": $templateName})
     */
    public function dynamicAction($templateName)
    {
        return ['data' => 'example'];
    }
    
  3. Integration with SensioFrameworkExtraBundle: Combine with @Template for mixed HTML/JSON responses:

    /**
     * @Route("/product/{id}", name="product_show")
     * @Template("@ApplicationMyBundle/Product/show.html.twig")
     * @JsonResponseTemplate("@ApplicationMyBundle/Product/show.json", options={"format": "json"})
     */
    public function showAction($id)
    {
        return ['product' => $this->findProduct($id)];
    }
    
  4. Data Transformation: Use templates to transform data before JSON serialization:

    // src/Application/MyBundle/Resources/views/Product/transform.json.php
    <?php
    return array_map(function($product) {
        return [
            'id' => $product->getId(),
            'name' => $product->getName(),
            'price' => (float) $product->getPrice()
        ];
    }, $products);
    

Workflows

  1. API Development:

    • Use templates for consistent JSON structures across endpoints.
    • Example: src/Application/MyBundle/Resources/views/API/Error/error.json.php for standardized error responses.
  2. Legacy System Integration:

    • Wrap legacy JSON logic in templates to avoid scattering business logic in controllers.
  3. Testing:

    • Mock templates in unit tests by overriding the JsonResponseTemplate annotation processor.

Gotchas and Tips

Pitfalls

  1. Template Caching: PHP templates are not cached by default. Use php engine configuration:

    twig:
        debug: false # Disable Twig debug to avoid caching issues
    
  2. Annotation Conflicts: @JsonResponseTemplate and @Template cannot coexist on the same method. Use separate actions or middleware to route based on Accept header.

  3. Data Serialization: PHP templates return raw arrays. Ensure all data is JSON-serializable (e.g., avoid DateTime objects without conversion):

    // Fix: Convert DateTime to string
    <?php return ['date' => $product->getCreatedAt()->format('Y-m-d')]; ?>
    
  4. Performance: Avoid complex logic in templates. Offload heavy processing to controllers or services.

Debugging

  1. Template Not Found: Verify the template path follows Symfony’s naming conventions: Bundle/Controller/Action/template.json.phpBundle/Resources/views/Controller/Action/template.json.php.

  2. Annotation Ignored: Ensure SensioFrameworkExtraBundle is installed and registered before BuJsonResponseBundle.

  3. Circular References: Use json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) in templates to handle circular references gracefully.

Tips

  1. Reuse Logic: Create helper templates (e.g., src/Application/MyBundle/Resources/views/Helpers/pagination.json.php) for common patterns like pagination.

  2. Validation: Validate template output with JSON Schema in a post-response event listener:

    $this->get('validator')->validate($jsonResponse, new \Symfony\Component\Validator\Constraints\Json());
    
  3. Extending the Bundle: Override the JsonResponseTemplateListener to add custom logic:

    // src/Application/MyBundle/EventListener/CustomJsonListener.php
    use Bu\JsonResponseBundle\EventListener\JsonResponseTemplateListener;
    
    class CustomJsonListener extends JsonResponseTemplateListener
    {
        protected function getTemplate($template, array $options)
        {
            // Custom logic here
            return parent::getTemplate($template, $options);
        }
    }
    

    Register in services.yml:

    services:
        application.my_bundle.json_listener:
            class: Application\MyBundle\EventListener\CustomJsonListener
            tags:
                - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
    
  4. Documentation: Add PHPDoc comments to templates for IDE autocompletion:

    /**
     * @param array $products List of Product entities
     * @return array JSON-serializable product data
     */
    <?php return array_map([$this, 'transformProduct'], $products); ?>
    
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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon