An easy way to format your domain objects to JSON is to use the Marshal Serializer.
Then pass the data to json_encode
and send the correct Content-Type header for your needs.
If you are using a framework like Symfony, you don't need to take care of setting the headers manually. There you can use the JsonResponse.
For example the correct Content-Type for dealing with Javascript would be application/javascript
.
Or if you need to support some pretty old browsers the safest would be text/javascript
.
For all other purposes like a mobile app use application/json
as the Content-Type.
Here is a small example:
<?php
...
$userCollection = [$user1, $user2, $user3];
$data = Marshal::serializeCollectionCallable(function (User $user) {
return [
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'birthday' => $user->getBirthday()->format('Y-m-d'),
'followers => count($user->getFollowers()),
];
}, $userCollection);
header('Content-Type: application/json');
echo json_encode($data);