gisostallenberg / response-content-negotiation-bundle
一个基于内容协商从控制器创建各种响应类型的包
2.0.0
2023-08-11 13:04 UTC
Requires
- php: >=7.3
- friendsofsymfony/rest-bundle: ^3.0
- symfony/config: ^6.0
- symfony/contracts: ^3.0
- symfony/dependency-injection: ^6.0
- symfony/event-dispatcher: ^6.0
- symfony/http-foundation: ^6.0
- symfony/http-kernel: ^6.0
- symfony/twig-bundle: ^6.0
- twig/twig: ^3.0
- willdurand/negotiation: ^3.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.6
- jms/serializer-bundle: ^4.0
- localheinz/composer-normalize: ^2.2
- maglnet/composer-require-checker: ^3.8
- phpstan/phpstan: ^0.12.8
- phpunit/phpunit: ^8.5
- sensiolabs/security-checker: ^6.0
- symfony/browser-kit: ^6.0
- symfony/debug-pack: ^1.0
- symfony/framework-bundle: ^6.0
README
响应内容协商包
一个基于内容协商从控制器创建各种响应类型的包
安装
composer require gisostallenberg/response-content-negotiation-bundle
要求
HTML
为了渲染HTML,该包需要 TwigBundle.
JSON & XML
为了输出JSON或XML,该包需要 FOS Rest Bundle 和 JMS Serializer Bundle 或 Symfony 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']])