LoginSignup
0

More than 3 years have passed since last update.

Guzzle最初の一歩

Last updated at Posted at 2021-02-22

ただのメモ。最初の最初の一歩を踏み出す

GuzzleUtil.php
<?php


namespace App\Service;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Message\ResponseInterface;

class GuzzleUtil
{
    private Client $client;

    public function __construct()
    {
        $this->client = new Client(['base_uri' => 'http://httpbin.org','timeout' => 2.0,]);
    }

    public function retrieveGetResponse(): ResponseInterface
    {
        return $this->client->get('/get');
    }

    public function getResponseAsync()
    {
        // Send an asynchronous request.
        $request = new Request('GET', 'http://httpbin.org');
        $promise = $this->client->sendAsync($request)->then(function ($response) {
            echo 'I completed! ' . $response->getStatusCode();
        });
        $promise->wait();
    }
}
GuzzleUtilTest.php
<?php

namespace App\Service;

use PHPUnit\Framework\TestCase;

class GuzzleUtilTest extends TestCase
{
    public function testGetStatusCode()
    {
        $g = new GuzzleUtil();
        $res = $g->retrieveGetResponse();
        $this->assertEquals(200, $res->getStatusCode());

        $g->getResponseAsync();
    }
}

image.png
:thumbsup:

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0