Mapper Mapping

Property Mapping

use Astral\Serialize\Attributes\InputName;
use Astral\Serialize\Attributes\OutputName;
use Astral\Serialize\Support\Mappers\{
    CamelCaseMapper, 
    SnakeCaseMapper, 
    PascalCaseMapper, 
    KebabCaseMapper
};
use Astral\Serialize\Serialize;

#[Groups('profile','api')]
class User extends Serialize {
    // Directly specify the mapping name
    #[InputName('user_name', groups: ['profile','api'])]
    #[OutputName('userName', groups: ['profile','api'])]
    public string $name;

    // Use a mapper for style conversion
    #[InputName(CamelCaseMapper::class, groups: ['profile','api'])]
    #[OutputName(SnakeCaseMapper::class, groups: ['profile','api'])]
    public int $userId;

    // Supports multiple mappings and groups
    #[InputName('profile-email', groups: 'profile')]
    #[OutputName('userEmail', groups: 'profile')]
    public string $email;
}

// Use different mapping strategies
$user = User::setGroups('profile')::from([
    'user_name' => 'Job',       // Mapped to $name
    'userId' => 123,           // Converted by CamelCaseMapper
    'profile-email' => 'user@example.com' // Only effective in 'profile' group
]);

// Apply different mappings on output
$userArray = $user->toArray();
// $userArray toArray:
// [
//     'userName' => 'Job',
//     'user_id' => '123',
//     'userEmail' => user@example.com,
// ]

Global Class Mapping

Grouped Usage of Global Class Mapping

Requires use with the Groups annotation

Custom Mapper

Tips: Property mapping takes precedence over class-level mapping

最后更新于