Installation
Get started with mdg-utils for PHP
One Composer package, mdgascar/mdg-utils, with every module as value objects and enums. PHP 8.3+, zero dependencies, same results as the JavaScript packages.
Installing with Composer
Section titled “Installing with Composer”-
Require the package
Section titled “Require the package”Terminal composer require mdgascar/mdg-utils -
Use a module
Section titled “Use a module”Each module is a class under
Mdgascar\MdgUtils. Read a number written in any common way and format it.signup.php <?phprequire __DIR__ . '/vendor/autoload.php';use Mdgascar\MdgUtils\Phone\PhoneNumber;use Mdgascar\MdgUtils\Phone\PhoneNumberFormat;$phone = PhoneNumber::parse('034 12 345 67');$phone->operator->displayName(); // 'Yas Madagascar'$phone->format(PhoneNumberFormat::International); // '+261 34 12 345 67' -
Handle bad input
Section titled “Handle bad input”parse()throwsMdgUtilsException.safeParse()returns the error code without throwing,tryParse()returnsnull.signup.php use Mdgascar\MdgUtils\ErrorCode;use Mdgascar\MdgUtils\Phone\PhoneNumber;$result = PhoneNumber::safeParse('031 12 345 67');$result->success; // false$result->error?->errorCode; // ErrorCode::UnknownOperatorPhoneNumber::tryParse('not a number'); // null -
Catch errors from every module the same way
Section titled “Catch errors from every module the same way”Every module throws
MdgUtilsException; itserrorCodeis the same code JavaScript reports.signup.php use Mdgascar\MdgUtils\MdgUtilsException;try {PhoneNumber::parse($userInput);} catch (MdgUtilsException $exception) {echo $exception->errorCode->value; // 'INVALID_FORMAT' | 'UNKNOWN_OPERATOR' | …}