Skip to content
GitHub

Installation

Get started with malagasy-intl for PHP

One Composer package, mdgascar/malagasy-intl, with every module as value objects and enums. PHP 8.3+, zero dependencies, same results as the JavaScript packages.

PHP 8.3, 8.4, 8.5
Dependencies None
Projects Any Composer project: plain PHP, WordPress, Slim, Laminas… For Laravel and Symfony, add malagasy-intl-laravel or malagasy-intl-symfony for validation, templates and database types.
  1. Terminal
    composer require mdgascar/malagasy-intl
  2. Each module is a class under Mdgascar\MalagasyIntl. Read a number written in any common way and format it.

    signup.php
    <?php
    require __DIR__ . '/vendor/autoload.php';
    use Mdgascar\MalagasyIntl\PhoneNumber\PhoneNumber;
    use Mdgascar\MalagasyIntl\PhoneNumber\PhoneNumberFormat;
    $phone = PhoneNumber::parse('034 12 345 67');
    $phone->operator->displayName(); // 'Yas Madagascar'
    $phone->format(PhoneNumberFormat::International); // '+261 34 12 345 67'
  3. parse() throws MalagasyIntlException. safeParse() returns the error code without throwing, tryParse() returns null.

    signup.php
    use Mdgascar\MalagasyIntl\ErrorCode;
    use Mdgascar\MalagasyIntl\PhoneNumber\PhoneNumber;
    $result = PhoneNumber::safeParse('031 12 345 67');
    $result->success; // false
    $result->error?->errorCode; // ErrorCode::UnknownOperator
    PhoneNumber::tryParse('not a number'); // null
  4. Catch errors from every module the same way

    Section titled “Catch errors from every module the same way”

    Every module throws MalagasyIntlException; its errorCode is the same code JavaScript reports.

    signup.php
    use Mdgascar\MalagasyIntl\MalagasyIntlException;
    try {
    PhoneNumber::parse($userInput);
    } catch (MalagasyIntlException $exception) {
    echo $exception->errorCode->value; // 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | …
    }