What are the advantages of using a Mapper class to convert objects to arrays in PHP?
When converting objects to arrays in PHP, using a Mapper class can provide a structured and reusable way to handle the conversion process. This allows for better organization of code and separation of concerns, making it easier to maintain and update the conversion logic. Additionally, using a Mapper class can improve code readability and make it easier to test the conversion functionality.
<?php
class UserMapper {
public static function objectToArray($user) {
return [
'id' => $user->getId(),
'username' => $user->getUsername(),
'email' => $user->getEmail(),
// add more properties as needed
];
}
}
class User {
private $id;
private $username;
private $email;
// constructor, getters, setters, etc.
public function getId() {
return $this->id;
}
public function getUsername() {
return $this->username;
}
public function getEmail() {
return $this->email;
}
}
$user = new User();
$user->setId(1);
$user->setUsername('john_doe');
$user->setEmail('john.doe@example.com');
$userArray = UserMapper::objectToArray($user);
print_r($userArray);