A PHP library for mapping external API data to PHP objects using PHP 8 attributes. This library helps you easily transform API responses into strongly-typed PHP objects with minimal boilerplate code.
- PHP 8.0+
Install the package via Composer:
composer require yeremi/schema-mapper
- Define your data class with attributes:
use Yeremi\SchemaMapper\Attributes\ApiSchema;
class User
{
#[ApiSchema(key: 'first_name')]
private string $firstName;
#[ApiSchema(key: 'last_name')]
private string $lastName;
#[ApiSchema(key: 'email')]
private string $email;
// Getters
public function getFirstName(): string
{
return $this->firstName;
}
public function getLastName(): string
{
return $this->lastName;
}
public function getEmail(): string
{
return $this->email;
}
}
- Use the normalizer to map your data:
use Yeremi\SchemaMapper\Normalizer\NormalizerInterface;
class MyUseCase {
public function __construct(
NormalizerInterface $normalizer
) {}
public function fetchSomeData(){
$response = [
'first_name' => 'John',
'last_name' => 'Doe',
'email' => '[email protected]'
];
$user = $this->normalizer->normalize($response, User::class);
echo $user->getFirstName(); // Outputs: John
}
}
- Map API responses to PHP objects using attributes
- Support for nested objects
- Type validation
- Nullable properties support
- Dependency injection ready with interfaces
The library throws specific exceptions:
TypeMismatchException
: When the data type doesn't match the property typeReflectionException
: When there are issues with class reflection
For more examples and advanced use cases, refer to the examples directory in the documentation.
This project is open source and licensed under the MIT License - see the LICENSE file for details.
If you encounter any problems or have any questions, please open an issue.