PHP code example of lemonade / component_postcode

1. Go to this page and download the library: Download lemonade/component_postcode library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lemonade / component_postcode example snippets


use Lemonade\Postcode\PostcodeFormatter;
use Lemonade\Postcode\CountryCode;
use Lemonade\Postcode\Exception\PostcodeException;
use Lemonade\Postcode\FormatterRegistry;

// initialize with default formatters
$registry  = new FormatterRegistry();          // IMMUTABLE REGISTRY
$formatter = new PostcodeFormatter($registry); // READONLY REFERENCE

try {
    $postcode = $formatter->format(CountryCode::CZ, '12000');
    // "120 00"
} catch (PostcodeException $e) {
    echo $e->getValue() . ' is invalid: ' . $e->getMessage();
}

use Lemonade\Postcode\CountryCode;
use Lemonade\Postcode\CountryPostcodeFormatter;
use Lemonade\Postcode\Exception\InvalidPostcodeException;
use Lemonade\Postcode\FormatterRegistry;
use Lemonade\Postcode\PostcodeFormatter;

$registry = new FormatterRegistry();

// Add custom formatter for Antarctica (AQ)
$registry = $registry->register(CountryCode::AQ, new class implements CountryPostcodeFormatter {
    public function format(string $postcode): string
    {
        if (preg_match('/^[0-9]{4}$/', $postcode) !== 1) {
            throw new InvalidPostcodeException($postcode);
        }
        return strtoupper($postcode);
    }
});

$formatter = new PostcodeFormatter($registry);

try {
    echo $formatter->format(CountryCode::AQ, '1231');
    // outputs "1231"
} catch (InvalidPostcodeException $e) {
    echo $e->getValue() . ' is invalid: ' . $e->getMessage();
}