How to Use the JsonSerializable Interface

Posted by Unknown on Friday, May 2, 2014

Over the past few years JSON has taken over as the king of data interchange formats. Before JSON, XML ruled the roost. It was great at modeling complex data but it is difficult to parse and is very verbose. JSON really took off with the proliferation of rich AJAX driven sites as it’s a very human readable format, quick to parse and its simple key/value representation cuts out all the verbosity of XML.


I think we could all agree that writing less code that in turn requires less maintenance and introduces less bugs is a goal we would all like to achieve. In this post, I’d like to introduce you to a little known interface that was introduced in PHP 5.4.0 called JsonSerializable.


Before the JsonSerializable interface was available, returning a JSON encoded representation of an object for a consuming service meant one of two things.


The Ugly


The first approach was to construct a data structure outside the object that contained all the data that we wanted to expose.



<?php

class Customer
{

private $email = null;
private $name = null;

public function __construct($email, $name)
{
$this
->email = $email;
$this
->name = $name;
}

public function getName()
{
return $this->name;
}

public function getEmail()
{
return $this->email;
}
}

$customer
= new Customer('customer@sitepoint.com', 'Joe');

$data
= [
'customer' => [
'email' => $customer->getEmail(),
'name' => $customer->getName()
]
];

echo json_encode
($data);


We used an array here to hold the data from the Customer object that we wanted to encode, but it could just as easily have been an StdClass.


Continue reading %How to Use the JsonSerializable Interface%




more

{ 0 comments... » How to Use the JsonSerializable Interface read them below or add one }

Post a Comment

Popular Posts