Symfony从第三方API获取

yvt65v4c  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(179)

我对“Symfony”很陌生,我想知道你如何从第三方API使用(Get),然后在控制器中打印出来。
我做了一个httpclient,就像https://symfony.com/doc/current/http_client.html一样
但是如何将$Content放到一个数组中,以便像在product控制器中硬编码一样使用呢?

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;

class ProductsController extends AbstractController
{
    #[Route('/products', name: 'products')]
    public function index(): Response
    {       
        $products = ["Test", "Test2". "Test3"];

        return $this->render('/products/index.html.twig',array(
                'products' => $products
            ));
    }
}
gzszwxb4

gzszwxb41#

正如已经提到的,您必须使用HTTPClient来实现这一点。
首先,通过composer安装它

composer require symfony/http-client

在您的控制器中,您必须写入以下内容:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class ProductsController extends AbstractController
{
    #[Route('/products', name: 'products')]
    public function index(HttpClientInterface $client): Response
    {       
        $response = $client->request('GET', 'API_URL');
        $products = $response->toArray();

        return $this->render('/products/index.html.twig',array(
            'products' => $products
        ));
    }
}

您还可以事先转储响应以用于测试目的:

$response = $client->request('GET', 'API_URL');
$products = $response->toArray(); // or $response->getContent();

dump($products);

toArray直接解析API的内容,并尝试从中创建数组。getContent以字符串形式给出响应。
更多信息,请参阅:https://symfony.com/doc/current/http_client.html

相关问题