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

Responders Bundle Laravel Package

amorvan/responders-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require amorvan/responders-bundle
    

    For Symfony 3.x without Flex, add the bundle to AppKernel.php:

    new Morvan\Bundle\RespondersBundle\MorvanRespondersBundle(),
    

    For Symfony 3.4+, 4.x, or 5.x, the bundle auto-registers in config/bundles.php.

  2. First Use Case: Inject a responder into a controller method and invoke it with parameters. Example:

    use Morvan\Bundle\RespondersBundle\Responders\JsonResponder;
    
    public function showData(JsonResponder $jsonResponder)
    {
        $data = ['key' => 'value'];
        return $jsonResponder($data); // Returns JSON response
    }
    
  3. Key Files:

    • src/Responders/ for responder classes.
    • config/services.yaml (if customization is needed).

Implementation Patterns

Common Workflows

  1. Controller Layer: Replace traditional return new Response() with responders for consistency.

    // Before
    return new JsonResponse($data);
    
    // After
    return $jsonResponder($data);
    
  2. Service Layer: Use responders in services to decouple response logic from business logic.

    public function process(Request $request, JsonResponder $jsonResponder)
    {
        $result = $this->businessLogic($request);
        return $jsonResponder($result);
    }
    
  3. API Responses: Standardize JSON responses with metadata (e.g., status, errors):

    return $jsonResponder($data, 200, ['X-Custom-Header' => 'value']);
    
  4. File Downloads: Stream files directly without manual headers:

    return $fileResponder('/path/to/file.pdf', 'report.pdf');
    
  5. View Rendering: Pass data to Twig templates cleanly:

    return $viewResponder('template.html.twig', ['articles' => $articles]);
    

Integration Tips

  • Dependency Injection: Responders are auto-wired; no manual binding required.
  • Customization: Extend responders by creating child classes (e.g., CustomJsonResponder).
  • Testing: Mock responders in unit tests to isolate logic:
    $this->mock(JsonResponder::class)
         ->shouldReceive('__invoke')
         ->once()
         ->with($data);
    

Gotchas and Tips

Pitfalls

  1. Symfony Version Mismatch: The bundle supports Symfony 3.4–5.x. Ensure your composer.json aligns with the package’s requirements. Fix: Update Symfony or check the releases.

  2. Twig Autoloading: If using ViewResponder, ensure Twig templates are in templates/ and autoloaded. Fix: Configure twig.paths in config/packages/twig.yaml:

    twig:
        paths: ['%kernel.project_dir%/templates']
    
  3. FileResponder Paths: $pathToFile must be a valid filesystem path or SplFileObject. Relative paths are resolved from the project root. Fix: Use absolute paths or realpath() for clarity.

  4. RedirectResponder Routes: Routes must exist; undefined routes throw RouteNotFoundException. Fix: Validate routes with bin/console debug:router.

Debugging

  • Response Headers: Inspect headers with dd($response->headers) to debug JsonResponder or FileResponder issues.
  • Twig Errors: Enable Twig debug mode in config/packages/dev/twig.yaml:
    twig:
        debug: true
    

Extension Points

  1. Custom Responders: Extend BaseResponder to add logic:

    class ApiJsonResponder extends JsonResponder {
        public function __invoke($data, int $status = 200, array $headers = [])
        {
            $data['meta'] = ['status' => $status];
            return parent::__invoke($data, $status, $headers);
        }
    }
    
  2. Override Defaults: Configure responders via DI (e.g., set default JSON encoding options):

    # config/services.yaml
    services:
        Morvan\Bundle\RespondersBundle\Responders\JsonResponder:
            arguments:
                $options: { JSON_PRETTY_PRINT: true }
    
  3. Event Listeners: Hook into responder lifecycle (e.g., modify responses globally):

    public function onKernelResponse(ResponseEvent $event)
    {
        $response = $event->getResponse();
        if ($response instanceof JsonResponse) {
            $response->setEncodingOptions(JSON_UNESCAPED_SLASHES);
        }
    }
    

Tips

  • Consistency: Use responders uniformly across controllers to reduce boilerplate.
  • Performance: For large files, FileResponder streams content efficiently (no full file load).
  • Documentation: The package lacks extensive docs, but the source code is straightforward.
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