hurnell / postcode-api-bundle
Symfony 4 的 postcodeapi.nu 包
v1.0.2
2019-05-22 10:29 UTC
Requires
- php: ^7.1.3
- ext-json: *
- galbar/jsonpath: ^1.0
- guzzlehttp/guzzle: ^6.0
- symfony/config: ^4.0
- symfony/dependency-injection: ^4.0
- symfony/http-foundation: ^4.0
- symfony/http-kernel: ^4.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-22 22:22:41 UTC
README
postcode-api-bundle
这是一个用于访问 Postcode API (postcodeapi.nu) 的荷兰邮政编码 API 的 Symfony 4 包。基于邮政编码、房屋编号和额外编号的组合创建一个 PostcodeModel 对象。
特性/需求
基于邮政编码、房屋编号和额外编号进行搜索。注意,某些邮政编码和房屋编号的组合需要额外的房屋编号,如果没有这个额外值,地址则不存在。
- ('2011XA', 20, '') 不是一个有效的组合。对于这个邮政编码和房屋编号的组合,额外编号必须是 'A'、'RD' 或 'ZW'。
- 对于 ('2011XA', 20, '') 的值,包将返回一个 InvalidNumberExtraException,错误信息为:“对于这个邮政编码和房屋编号的组合,房屋编号的额外值必须是 (A, RD, ZW)。”
安装
- 通过 composer 下载。
- 通过在 config/bundles.php 中添加类引用来启用包(如果 composer 没有为你做这个)。
- 创建 yaml 配置文件 config/packages/hurnell_postcode_api.yaml,并引用你的 api_key。
1 - 通过 composer 下载
composer require hurnell/postcode-api-bundle:*
2 - 启用包
# config/bundles.php Hurnell\PostcodeApiBundle\HurnellPostcodeApiBundle::class => ['all' => true],
3 - 使用 API 密钥进行配置
# config/packages/hurnell_postcode_api.yaml hurnell_postcode_api: api_key: 'your_api_key'
用法
默认启用自动注入,因此在控制器操作(或其他类的构造函数)中
<?php use Hurnell\PostcodeApiBundle\Service\PostcodeApiClient; // use Exception classes class MyController extends AbstractController { public function getPostcodeAction(PostcodeApiClient $client){ $form = $this->createForm(PostcodeFormType::class); try { $postcodeModel = $client ->makeRequest( '2011XC', 20, 'RD' ) ->populatePostcodeModel(); $postcodeModel->getStreet(); // Doelstraat $postcodeModel->getCity(); // Haarlem // $postcodeModel-> get etc etc // json response return $this->json($postcodeModel->toArray()); } catch (InvalidApiResponseException|InvalidPostcodeException $e) { // handle exception } catch (InvalidHouseNumberException $e) { // handle exception $form->get('number')->addError(new FormError($e->getMessage())); } catch (InvalidNumberExtraException $e) { // handle exception $postcodeModel = $client->populatePostcodeModelWithoutExtra(); return $this->json( array_merge( $postcodeModel->toArray(), ['warning'=>$e->getMessage()] ) ); } } }
处理 InvalidNumberExtraException
注意,无效的额外编号值不是关键问题。此外,API 也不是完美的;房屋编号的额外编号有遗漏。
存在 populatePostcodeModelWithoutExtra 方法用于这些情况
try { $postcodeModel = $client ->makeRequest( '2011XC', 20, 'RD' ) ->populatePostcodeModel(); // ... } catch (InvalidNumberExtraException $e) { $postcodeModel = $client->populatePostcodeModelWithoutExtra(); return $this->json( array_merge( $postcodeModel->toArray(), ['warning'=>$e->getMessage()] ) ); }