Wizard
Wizard

Reputation: 11295

PHP object mapping best way

Creating Rest API I'm has accoutred with problem.

Our client given us request, that he want to send for us:

json example:

    {
    "request": {
        "name": "John",
        "surname": "Snow",
        "age": "19"
    }
}

My User model class looks like:

class User
{
    public $firstName;

    public $latName;

    public $age;
}

What is best way to set object from given json ? Using some existing libraries or write custom mapper ?

I'm not interested on inventing bicycle.

Upvotes: 2

Views: 5184

Answers (1)

martin
martin

Reputation: 96959

I'd personally go with:

class User
{
    public static function fromArray($array)
    {
        $user = new User();
        $user->firstName = $array['name'];
        ...
        return $user;
    }
}

Then instantiating with:

$user = User::fromArray($responseFromWhatever);

Upvotes: 6

Related Questions