solidworx/simple-response-bundle

一个用于在控制器中返回简单响应的 Symfony 扩展包

0.3.0 2020-03-03 07:14 UTC

This package is auto-updated.

Last update: 2024-08-29 04:48:28 UTC


README

SimpleResponseBundle 是一个为 Symfony 框架提供的扩展包,它允许你在控制器/操作中返回自定义的响应类,从而减少控制器或操作所需的依赖项。

安装

使用 composer 安装扩展包,运行以下命令:

$ composer require solidworx/simple-response-handler

安装扩展包后,你需要在你的应用程序中注册该扩展包

<?php

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            ...
            new SolidWorx\SimpleResponseBundle\SimpleResponseBundle(),
            ...
        ];
        
        ...        
     }
}

使用

此扩展包包含一些预定义的处理程序

  • 模板响应
  • 路由重定向响应

模板响应

TemplateResponse 类将根据类的参数渲染模板。要在操作中渲染模板,只需返回一个 TemplateResponse 类的实例即可

<?php

// src/AppBundle/Action/MyAction.php

use SolidWorx\SimpleResponseBundle\Response\TemplateResponse;

class MyAction
{
    public function __invoke()
    {
        return new TemplateResponse('index.html.twig');
    }
}

加载此操作时,index.html.twig 模板将自动渲染,无需在操作类中包含 twig 依赖。

路由重定向响应

RouteRedirectResponse 类将重定向到指定的路由名称。

<?php

// src/AppBundle/Action/MyAction.php

use SolidWorx\SimpleResponseBundle\Response\RouteRedirectResponse;

class MyAction
{
    public function __invoke()
    {
        return new RouteRedirectResponse('_some_route_name');
    }
}

加载此操作时,页面将重定向到 _some_route_name 路由,无需在操作中包含路由器或生成 URL。

注册自定义处理程序

要注册自定义处理程序,你需要创建一个新的服务,该服务具有 response_handler.handler 标签。这个类需要实现 SolidWorx\SimpleResponseBundle\ResponseHandlerInterface 接口

services:
    My\Custom\Handler:
        arguments: ['@doctrine.orm.entity_manager']
        tags: ['solidworx.response_handler']
            

然后你需要创建一个类,该类将在你的操作中用作返回值

<?php
use Symfony\Component\HttpFoundation\JsonResponse;

class DoctrineEntityResponse extends JsonResponse
{
    private $entity;
    
    public function __construct(string $entity)
    {
        $this->entity = $entity;
        parent::__construct();
    }

    public function getEntity(): string
    {
        return $this->entity;
    }
}      

你的处理程序类将添加返回响应对象的逻辑;

<?php
use SolidWorx\SimpleResponseBundle\ResponseHandlerInterface;
use Symfony\Component\HttpFoundation\Response;

class Handler implements ResponseHandlerInterface
{
    private $em;

    public function __construct($entityManager)
    {
        $this->em = $entityManager;
    }
    
    public function supports(Response $object): bool
    {
        return $object instanceof DoctrineEntityReponse; // Only support responses of this type
    }
    
    public function handle(Response $object): Response
    {
        return $object->setData($this->em->getRepository($object->getEntity())->findAll()); // Return all records in the entity as a JSON response
    }
}

然后你可以在你的操作中使用你的新类

<?php

// src/AppBundle/Action/MyAction.php

class MyAction
{
    public function __invoke()
    {
        return new DoctrineEntityResponse(\App\Entity\Order::class); // Pass the Order entity which will return all orders in a JSON response
    }
}