使用Slim+Guzzle从PHP应用程序进行异步API调用

使用Slim+Guzzle从PHP应用程序进行异步API调用,php,api,asynchronous,slim,guzzle,Php,Api,Asynchronous,Slim,Guzzle,我正在使用Slim框架开发一个php应用程序。我的应用程序主页正在进行大约20次RESTAPI调用,这降低了页面负载 我读到,我可以使用像Guzzle这样的Http客户端异步调用这些API,但我找不到任何关于如何将Guzzle与Slim结合使用的文章 有人能告诉我怎么用Slim的Guzzle吗 或者是否有其他解决方案可以加快页面加载 注意:我是PHP的新手,要在Slim中使用Guzzle,您需要 通过运行composer安装它 $ composer require guzzlehttp/guzz

我正在使用Slim框架开发一个php应用程序。我的应用程序主页正在进行大约20次RESTAPI调用,这降低了页面负载

我读到,我可以使用像Guzzle这样的Http客户端异步调用这些API,但我找不到任何关于如何将Guzzle与Slim结合使用的文章

有人能告诉我怎么用Slim的Guzzle吗

或者是否有其他解决方案可以加快页面加载


注意:我是PHP的新手,要在Slim中使用Guzzle,您需要

通过运行composer安装它

$ composer require guzzlehttp/guzzle:~6.0

例如,创建依赖项注册

<?php

use GuzzleHttp\Client;

$container = $app->getContainer();

$container['httpClient'] = function ($cntr) {
    return new Client();             
};
例如,如果您有以下路线

$app->get('/example', App\Controllers\Example::class);
和控制器示例如下

<?php
namespace App\Controllers;

use GuzzleHttp\ClientInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Example
{
    private $httpClient;

    public function __construct(ClientInterface $httpClient) 
    {
        $this->httpClient = $httpClient;
    }

    public function __invoke(Request $request, Response $response, array $args)
    {
        //call api, etc..etc
       $apiResponse = $this->httpClient->get('http://api.blabla.org/get');
       //do something with api response
       return $response;
    }
}
为了加快页面加载速度,如果您是API开发人员,请从这里开始。如果您不是API开发人员并且没有控制权,请尝试思考是否可以通过删除非必要的API调用来减少API调用的数量。或者,作为最后的手段,将API调用响应缓存到存储中,以便应用程序在以后检索时更快

例如使用redis。
您可以计算API url调用的哈希值,包括其查询字符串,并使用哈希值作为键来访问缓存的API调用响应。

请向我们展示一些页面加载功能的示例代码。在web服务器请求上运行的slim应用程序CMIIW将在单线程中运行。所以异步调用在这里不相关。您可以让php在cli上使用带有pthread扩展的多线程。我的建议是缓存api响应,例如,使用redis、文件或数据库。@ZamronyP.Juhara是正确的。异步请求在这里不会起多大作用-缓存将是一种更好的方法。或者减少呈现页面所需的请求数—需要20个请求似乎太多了。
<?php
namespace App\Controllers;

use GuzzleHttp\ClientInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

class Example
{
    private $httpClient;

    public function __construct(ClientInterface $httpClient) 
    {
        $this->httpClient = $httpClient;
    }

    public function __invoke(Request $request, Response $response, array $args)
    {
        //call api, etc..etc
       $apiResponse = $this->httpClient->get('http://api.blabla.org/get');
       //do something with api response
       return $response;
    }
}
use App\Controllers\Example;

$container[Example::class] = function ($cntr) {
    return new Example($cntr->httpClient);
}