bu / json-response-bundle
Symfony2 扩展包,允许使用模板来处理 JSON 响应
1.0.1
2014-10-17 18:36 UTC
Requires
- php: >=5.3.2
- sensio/framework-extra-bundle: 2.3.*
- symfony/framework-bundle: >=2.1,<2.4-dev
This package is not auto-updated.
Last update: 2024-09-21 11:46:42 UTC
README
BuJsonResponseBundle 帮助您以与 HTML 响应模板相同的方式使用模板来处理 JSON 响应,让您在需要以 JSON 格式返回数据时,能够分离业务逻辑和数据展示。
基于 SensioFrameworkExtraBundle 中的 @Template 注解,并需要它。
安装
使用 composer 添加扩展包
composer require bu/json-response-bundle dev-master
在您的 symfony 配置中启用 php 模板引擎
# app/config/config.yml framework: # ... templating: engines: ['twig', 'php']
在 AppKernel.php 中注册扩展包
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new Bu\JsonResponseBundle\BuJsonResponseBundle(), ); }
使用方法
示例控制器
<?php namespace Application\MyBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Bu\JsonResponseBundle\Configuration\JsonResponseTemplate; class ProductController extends Controller { /** * @JsonResponseTemplate */ public function listAction() { return array('products' => $this->get('my.product.service')->getAllProducts()); } }
listAction 的 JSON 模板
<?php // Resources/view/Product/list.json.php $data = array(); foreach ($products as $product) { $data[$product->getStatus()][] = array( 'name' => $product->getName(), 'description' => $product->getDescription(), 'relationsCount' => count($product->getRelations()), 'isRequiresCheck' => $product->isRequiresCheck(), ); } $view['jsonResponse']->output($data);
此外,还有一个简单的 JsonResponse 类,如果您已经准备好了数据,可以使用它
use Bu\JsonResponseBundle\HttpFoundation\JsonResponse; public function deleteAction(Product $product) { $this->get('my.product.service')->delete($product); return new JsonResponse(array('success' => true)); }
从 Symfony 2.7 开始,有一个类似的内部类 Symfony\Component\HttpFoundation\JsonResponse https://symfony.com.cn/doc/2.7/components/http_foundation.html#creating-a-json-response
许可协议
此扩展包受 MIT 许可协议的约束。