# Symfony

[`ideal-postcodes/symfony-bundle`](https://packagist.org/packages/ideal-postcodes/symfony-bundle) configures the [PHP SDK](/docs/sdks/php.md) from your application config and lets you inject the client into a controller or service. It supports Symfony 6.4, 7 and 8 on PHP 8.2 or later.

## How do I install the bundle?

```bash
composer require ideal-postcodes/symfony-bundle
```

Symfony Flex registers the bundle. Without Flex, add it to `config/bundles.php`:

config/bundles.phpphp

```php
return [
    // ...
    IdealPostcodes\Symfony\IdealPostcodesSymfonyBundle::class => ['all' => true],
];
```

## How do I configure it?

Set your API key, and the Management Key if you manage keys, licensees or configurations from this application. Both belong in environment variables, never in a committed file.

config/packages/ideal\_postcodes.yamlyaml

```yaml
ideal_postcodes:
    api_key: '%env(IDPC_API_KEY)%'
    management_key: '%env(IDPC_MANAGEMENT_KEY)%'
```

.env.localbash

```bash
IDPC_API_KEY=ak_test
IDPC_MANAGEMENT_KEY=uk_...
```

| Option           | Purpose                                                                                                                 |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `api_key`        | Required. Your API key, or a licensee key beginning `sl_`                                                               |
| `management_key` | Your Management Key for key, licensee and configuration operations. Leave it unset elsewhere                            |
| `base_uri`       | Defaults to `https://api.ideal-postcodes.co.uk/v1`                                                                      |
| `http_client`    | Service id of a PSR-18 client to send requests with. See below for the default                                          |
| `headers`        | Headers sent with every request. A `User-Agent` naming your application is sent ahead of the bundle and SDK identifiers |

## How do I use the client?

Type-hint `IdealPostcodes\Client`. It is a private, autowirable service, also under `IdealPostcodes\Contracts\ClientContract`.

src/Controller/AddressController.phpphp

```php
use IdealPostcodes\Client;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

final class AddressController
{
    public function __construct(private readonly Client $client) {}

    #[Route('/addresses/{postcode}')]
    public function byPostcode(string $postcode): JsonResponse
    {
        $lookup = $this->client->lookup($postcode);

        return new JsonResponse([
            'found' => $lookup->found,
            'addresses' => $lookup->addresses,
            'suggestions' => $lookup->suggestions,
        ]);
    }

    #[Route('/suggest')]
    public function suggest(string $query): JsonResponse
    {
        return new JsonResponse($this->client->findAddress(['query' => $query])->result->hits);
    }
}
```

Response objects are `JsonSerializable`, so `JsonResponse` renders them with the API's field names.

Each API operation is one method on the client, such as `addressCleanse()` or `keyUsage()`. The [endpoints reference](/docs/sdks/php/endpoints.md) lists them all. The service id is `ideal_postcodes.client`.

## Which HTTP client sends the requests?

The bundle uses the `Psr\Http\Client\ClientInterface` service when your application has one. Symfony's HttpClient component registers it once a PSR-17 factory is installed:

```bash
composer require symfony/http-client nyholm/psr7
```

Timeouts, retries and proxies then come from `framework.http_client`:

config/packages/framework.yamlyaml

```yaml
framework:
    http_client:
        default_options:
            timeout: 5
```

Without that service, the SDK discovers any installed PSR-18 client, such as Guzzle. To use a specific client, set `http_client` to its service id.

## How do I test code that uses the SDK?

Replace the HTTP client in the test environment with a mock that answers from fixtures. `php-http/mock-client` is a PSR-18 client that returns queued responses.

```bash
composer require --dev php-http/mock-client
```

config/services\_test.yamlyaml

```yaml
services:
    Http\Mock\Client: ~

ideal_postcodes:
    api_key: ak_test
    http_client: Http\Mock\Client
```

tests/AddressControllerTest.phpphp

```php
$mock = static::getContainer()->get(Http\Mock\Client::class);
$mock->addResponse(new Nyholm\Psr7\Response(200, ['Content-Type' => 'application/json'], $postcodeBody));

$client->request('GET', '/addresses/BR8 7RE');
```

Errors are the SDK's own exceptions. See [error handling](/docs/sdks/php/errors.md).
