Martyn is a software engineer working for a civil engineering company. He has a thirst for learning and enjoys contributing to OSS projects. He has a deep interest in tools and techniques that improve coding practice on a personal and team level. He also enjoys providing and receiving support via the PHP Mentoring initiative.

Martyn's articles

  1. How to Use the JsonSerializable Interface

    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.