php - 如何在 symfony 4 中处理来自外部源的 GET 请求?
问题描述
我正在尝试使用某种字符串数组的 JSON 响应来处理 symfony 4 中的 GET 请求。如何在我的 Symfony 4 应用程序中处理请求?我使用控制器还是服务?
解决方案
我建议您首先确定您的代码结构并坚持下去。
建议使用控制器,它通过扩展 AbstractController.php 为您提供额外的好处。
控制器是您创建的 PHP 函数,它从 Request 对象中读取信息并创建并返回 Response 对象。响应可能是 HTML 页面、JSON、XML、文件下载、重定向、404 错误或其他任何内容。控制器执行应用程序呈现页面内容所需的任意逻辑。来源
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class TestController
* @package App\Controller
*/
class TestController extends AbstractController
{
/**
* @Route(path="test", name="test", methods={"GET"})
* @param Request $request
* @return JsonResponse
*/
public function index(Request $request): JsonResponse
{
$test['a'] = 'A';
$test['b'] = 'B';
$test['c'] = 'C';
return new JsonResponse($test);
}
}
希望这可以帮助!
推荐阅读
- python - 在 Python 中使用 sklearn.preprocessing 进行数据转换
- php - 试图检查 id 是否存在
- javascript - 通过 jQuery 将类添加到 div onclick
- jquery - 遍历javascript数组并在key等于或小于时输出值
- git - 在给定提交哈希的情况下搜索 git 日志
- aframe - Aframe 0.9.0 设置属性
- java - 使用自定义字体而不安装
- php - 如何在刀片、laravel 中添加简写 if 语句?
- coldfusion - 尝试使用 ColdFusion 11 实现 SAML 2.0
- python - 根据 Pandas 中的其他信息更改数据框中列的一部分