12/08/2018, 13:26

Giới thiệu Guzzle 6

Guzzle là một PHP HTTP client giúp việc gửi HTTP request trở lên đơn giản. Phiên bản mới nhất là Guzzle 6. Các lợi thế của Guzzle 6: Dễ dàng thực hiện tạo query string, POST request, streaming large upload, streaming large download, sử dụng HTTP cookies, upload dữ liệu Json.... Có thể ...

Guzzle là một PHP HTTP client giúp việc gửi HTTP request trở lên đơn giản. Phiên bản mới nhất là Guzzle 6. Các lợi thế của Guzzle 6:

  • Dễ dàng thực hiện tạo query string, POST request, streaming large upload, streaming large download, sử dụng HTTP cookies, upload dữ liệu Json....

  • Có thể gửi cả request đồng bộ và không đồng bộ bằng cách sử dụng cùng một interface.

  • Sử dụng tiểu chuẩn PSR-7 cho request, response, stream. Điều này giúp bạn dễ dàng tích hợp các thư viện khác sử dụng PSR-7 với Guzzle. (Các phiên bản trước không sử dụng PSR-7)

  • Không phụ thuộc chặt vào cURL, PHP stream, sockets hoặc vòng lặp không bị chặn.

  • Hệ thống Middleware cho phép bạn kiểm soát hành vi của client

I. Cài đặt I.1. Yêu cầu:

  • PHP >= 5.5.0
  • Để sử dụng PHP stream handler, allow_url_fopen cần được kích hoạt trong file php.ini trên hệ thống của bạn.
  • Để sử dụng cURL handler, bạn cần có phiên bản cURL >= 7.19.4 biên dịch cùng OpenSSL và zlib

Ghi chú: Guzzle không còn yêu cầu cURL để gửi HTTP request. Guzzle sẽ sử dụng PHP stream wrapper để gửi HTTP requests nếu cURL không được cài đặt. Ngoài ra bạn cũng có thể sử dụng HTTP handler của riêng mình để gửi request. I.2 Cài đặt Bạn nên cài đặt thông qua composer

 composer require guzzlehttp/guzzle:~6.0

Bạn có thể trong file composer.json của bạn

     {
       "require": {
          "guzzlehttp/guzzle": "~6.0"
       }
    }

Sau khi cài đặt bạn cần required Composer's autoloader require 'vendor/autoload.php'; II. Sử dụng II.1 Tạo Request Bạn có thể gửi request với Guzzle sử dụng GuzzleHtppClientInterface object.

  • Tạo một Client
    use GuzzleHttpClient;

    ....

    $client = new Client([
            // Base URI được sử dụng với request
            'base_uri' => 'http://httpbin.org',
    ]);
base_uri: ( có thể là chuỗi hoặc một thể hiện của UriInterface) Can be a string or instance of UriInterface. Base URI của client sẽ được kết hợp với đường dẫn tương đối.

Ví dụ
    // Tạo một client với một base URI
    $client = new GuzzleHttpClient(['base_uri' => 'https://foo.com/api/']);
    // Gửi một request đến https://foo.com/api/test
    $response = $client->request('GET', 'test');
    // Gửi một request đến https://foo.com/root
    $response = $client->request('GET', '/root');
  • Gửi Request

    Magic method khiến việc gửi request đồng bộ hết sức đơn giản:

        $response = $client->get('http://httpbin.org/get');
        $response = $client->delete('http://httpbin.org/delete');
        $response = $client->head('http://httpbin.org/get');
        $response = $client->options('http://httpbin.org/get');
        $response = $client->patch('http://httpbin.org/patch');
        $response = $client->post('http://httpbin.org/post');
        $response = $client->put('http://httpbin.org/put');
Bạn cũng có thể tạo một Request và gửi nó với Client đã tạo.
        use GuzzleHttpPsr7Request;

        ...

        $request = new Request('PUT', 'http://httpbin.org/put');
        $response = $client->send($request, ['timeout' => 2]);
  • Request không đồng bộ

    Bạn có thể gửi request không đồng bộ bằng magic method được cung cấp bởi client:

    $promise = $client->getAsync('http://httpbin.org/get');
    $promise = $client->deleteAsync('http://httpbin.org/delete');
    $promise = $client->headAsync('http://httpbin.org/get');
    $promise = $client->optionsAsync('http://httpbin.org/get');
    $promise = $client->patchAsync('http://httpbin.org/patch');
    $promise = $client->postAsync('http://httpbin.org/post');
    $promise = $client->putAsync('http://httpbin.org/put');
Hoặc bạn có thể tạo request và gửi đi tương tự như Request đồng bộ
    use GuzzleHttpPsr7Request;

    // Khởi tạo một PSR-7 request object
    $headers = ['X-Foo' => 'Bar'];
    $body = 'Hello!';
    $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);

    // Và gửi đi
    $promise = $client->sendAsync($request);

    // Hoặc, nếu bạn không muốn gửi cả thể hiện của request:
    $promise = $client->requestAsync('GET', 'http://httpbin.org/get');

II.2 Sử dụng response

Trong các ví dụ trên chúng ta sử dụng biến response để chứa thông tin phản hồi. response sẽ là một thể hiện của PSR-7 response, PsrHttpMessageResponseInterface và chứa rất nhiều thông tin hữu ích

Bạn có thể lấy thông tin status code và reason phare:

$code = $response->getStatusCode(); // 200
$reason = $response->getReasonPhrase(); // OK

$code = $response->getStatusCode(); // 404
$reason = $response->getReasonPhrase(); // Not Found

Lấy thông tin header

// Kiểm tra xem có header hay không.
if ($response->hasHeader('Content-Length')) {
    echo "It exists";
}

// Lấy thông tin header.
echo $response->getHeader('Content-Length');

// Lấy tất cả các header.
foreach ($response->getHeaders() as $name => $values) {
    echo $name . ': ' . implode(', ', $values) . "
";
}

Body của một response được lấy bằng cách sử dụng phương thức getBody(). Body có thể sử dụng như là một chuỗi string hoặc 1 stream

$body = $response->getBody();
// Sử dụng như một string
echo $body;
// Sử dụng như một stream
$tenBytes = $body->read(10);
// Đọc nội dung còn lại như một string
$remainingBytes = $body->getContents();

II.3 Query String

Bạn có thể gửi query string trong uri

$response = $client->request('GET', 'http://httpbin.org?foo=bar');

Điều này khá là phiền phức nếu query string của bạn quá dài, lúc đó bạn nên sử dụng tùy chọn query

$client->request('GET', 'http://httpbin.org', [
    'query' => ['foo' => 'bar']
]);

Tùy chọn query sử dụng PHP's http_build_query để định dạng query string.

II.4 Uploading Data

Guzzle cung cấp cho bạn một số cách khá hiệu quả để upload data.

Bạn có thể gửi một request chứa một stream với dữ liệu là chuỗi string, resource nhận được từ fopen hoặc một thể hiện của PsrHttpMessageStreamInterface

// Một string.
$r = $client->request('POST', 'http://httpbin.org/post', [
    'body' => 'raw data'
]);

// Một resource.
$body = fopen('/path/to/file', 'r');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);

// Sử dụng phương thức stream_for() để tạo một PSR-7 stream.
$body = GuzzleHttpPsr7stream_for('hello!');
$r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);

Nếu bạn muốn upload json data, hãy sử dụng tùy chọn json

$r = $client->request('PUT', 'http://httpbin.org/put', [
    'json' => ['foo' => 'bar']
]);
  • POST/Form Requests

    • Gửi form fields

    Để gửi application/x-www-form-urlencoded POST requests bạn cần tùy chọn form_params

  $response = $client->request('POST', 'http://httpbin.org/post', [
    'form_params' => [
        'field_name' => 'abc',
        'other_field' => '123',
        'nested_field' => [
            'nested' => 'hello'
        ]
    ]
    ]);
  • Gửi form file

Nếu bạn cần gửi 1 file trong POST request (multipart/form-data POST requests) sử dụng multipart option. multipart nhận một array của array. Mỗi array con gồm :

name: (required, string) tên của field.

contents: (required, mixed) Bạn có thể gửi một request chứa một stream với dữ liệu là chuỗi string, resource nhận được từ fopen hoặc một thể hiện của PsrHttpMessageStreamInterface

      $response = $client->request('POST', 'http://httpbin.org/post', [
            'multipart' => [
                [
                    'name'     => 'field_name',
                    'contents' => 'abc'
                ],
                [
                    'name'     => 'file_name',
                    'contents' => fopen('/path/to/file', 'r')
                ],
                [
                    'name'     => 'other_file',
                    'contents' => 'hello',
                    'filename' => 'filename.txt',
                    'headers'  => [
                        'X-Foo' => 'this is an extra header to include'
                    ]
                ]
            ]
    ]);
  • Cookie

Guzzle có thể thay đổi cookie session nếu bạn sử dụng tùy chọn cookie. Khi gửi request cookie bắt buộc phải là một thể hiện của GuzzleHttpCookieCookieJarInterface

      $jar = new GuzzleHttpCookieCookieJar;
        $r = $client->request('GET', 'http://httpbin.org/cookies', [
        'cookies' => $jar
    ]);

III. Tổng Kết Guzzle 6 là 1 package mạnh mẽ giúp ích rất tốt cho bạn trong việc gửi PHP HTTP request. Nó rất thích hợp khi bạn làm việc với API

0