首页 > 解决方案 > 如何在 symfony 4 中处理来自外部源的 GET 请求?

问题描述

我正在尝试使用某种字符串数组的 JSON 响应来处理 symfony 4 中的 GET 请求。如何在我的 Symfony 4 应用程序中处理请求?我使用控制器还是服务?

标签: phpsymfonycurl

解决方案


我建议您首先确定您的代码结构并坚持下去。
建议使用控制器,它通过扩展 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);
    }
}

希望这可以帮助!


推荐阅读