freshheads/postcode-api-client

postcodeapi.nu 网络服务的客户端库。

4.1.1 2022-04-15 15:02 UTC

This package is auto-updated.

Last update: 2024-09-15 19:47:47 UTC


README

Build Status

FHPostcodeAPIClient 是一个用于 PostcodeAPI.nu 网络服务的 PHP 客户端库。这个库由 Freshheads 开发,并将与网络服务本身同步维护。

链接

安装

FHPostcodeAPIClient 可以通过 Composer 容易地安装。

composer require freshheads/postcode-api-client

用法

实例化客户端,并用您的个人凭证替换 API 密钥

// Use the composer autoloader to load dependencies
require_once 'vendor/autoload.php';

// initiate client
$apiKey = 'replace_with_your_own_api_key';
// In this example we made use of the Guzzle as HTTPClient.
$client = new \FH\PostcodeAPI\Client(
    new GuzzleHttp\Client([
        'headers' => [
            'X-Api-Key' => $apiKey
        ]
    ])
);

// call endpoints
$response = $client->getAddresses('5041EB', 21);
$response = $client->getAddress('0855200000061001');
$response = $client->getPostcodeDataByPostcode('5041EB');

// Note that this call is only available with a premium account
$response = $client->getPostcodes('51.566405', '5.077171');

在 Symfony 项目中

我们建议使用 Guzzle,以便能够将 Guzzle 与 PostcodeApiClient 结合使用。以下定义是使用 Guzzle 7 的实现。

_defaults:
        autowire: true
        autoconfigure: true

    project.http.client.postal_code:
        class: GuzzleHttp\Client
        bind:
            $config: { headers: { X-Api-Key: '%postcode_api_nu.key%' } }

    FH\PostcodeAPI\Client:
        $httpClient: '@project.http.client.postal_code'

现在您应该能够使用 FH\PostcodeAPI\Client 服务向 PostcodeAPI 发送请求。

Guzzle 6

为了使用 Guzzle 6,您还应该使用 Guzzle6Adapter。运行以下命令将自动安装 Guzzle。

composer require php-http/guzzle6-adapter

然后添加以下服务定义(适用于 Symfony ^3.4)

services:
    _defaults:
        autowire: true
        autoconfigure: true

    project.http.guzzle.client:
        class: GuzzleHttp\Client
        arguments:
            - { headers: { X-Api-Key: 'replace_with_your_own_api_key_or_variable' } }
    
    project.http.adapter.guzzle.client:
        class: Http\Adapter\Guzzle6\Client
        arguments:
            $client: '@project.http.guzzle.client'
    
    FH\PostcodeAPI\Client:
        $httpClient: '@project.http.adapter.guzzle.client'