gisostallenberg/response-content-negotiation-bundle

一个基于内容协商从控制器创建各种响应类型的包

2.0.0 2023-08-11 13:04 UTC

README

Latest Stable Version Latest Unstable Version Total Downloads License

响应内容协商包

一个基于内容协商从控制器创建各种响应类型的包

安装

composer require gisostallenberg/response-content-negotiation-bundle

要求

HTML

为了渲染HTML,该包需要 TwigBundle.

JSON & XML

为了输出JSON或XML,该包需要 FOS Rest BundleJMS Serializer BundleSymfony Serializer

用法

<?php

namespace App\Controller;

use GisoStallenberg\Bundle\ResponseContentNegotiationBundle\Content\ResultData;
use GisoStallenberg\Bundle\ResponseContentNegotiationBundle\Content\ResultInterface;
use GisoStallenberg\Bundle\ResponseContentNegotiationBundle\Content\ResultServiceLocator;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class AcmeController
{
    /**
     * @Route("/my-page", methods={"GET"})
     */
    public function resultAction(
        ResultServiceLocator $resultServiceLocator,
        Request $request
    ): ResultInterface {
        return $resultServiceLocator->getResult($request, new ResultData('acme', ['my-data-label' => 'my data']));
    }
}

HTML

这将使用 Twig 上下文 ['my-data-label' => 'my data'] 渲染 acme.html.twig.

如果你想要渲染一个特定的模板,你可以将这个作为 template 参数添加到 ResultData 中。例如

new ResultData('acme', ['my-data-label' => 'my data'], ['template' => '@AcmeBundle/templates/acme.twig.html'])

这将使用 Twig 上下文 ['my-data-label' => 'my data'] 渲染 @AcmeBundle/templates/acme.twig.html.

JSON

这将返回

{
  "my-data-label": "my data"
}

XML

这将返回

<my-data-label>
    <entry>my data</entry>
<my-data-label>

序列化

为了在序列化过程中使用序列化组,你可以添加 groups 选项参数。例如

new ResultData('acme', ['my-data-label' => 'my data'], ['groups' => ['profile', 'list']])