hal+json embedded inside embedded (Multiple/Nested embedded)

HAL (Hypertext Application Language) is a new standard for RESTFUL web services. The HAL rfc is still in draft at the time of this post, however, the main goal of the HAL standard is to provide a more convenient and easy way to expose resources within your API. The _links reserved property allows resources to link to other resources via a href. Any client consuming the API can simply follow the links served by the back end. See below for an example;

{
    "_links": {
        "self": { "href": "/" },
        "contact": { "href": "/contact" }
        "about": { "href": "/about" }
    },
    ...
}

When sending a GET request on a collection to an API that uses HAL, a number of resources will be populated in the _embedded property. This is another reserved property used by HAL. A collection of embedded resources may look like below;

{
    "_links": {
        "self": { "href": "/invoices" }
    },
    "_embedded": {
        "invoices": [
            {
                "_links": {
                    "self": { "href": "/invoice/1" }
                },
                "id": 1,
                "total": 2.99,
                "no_items": 1
            },
            {
                "_links": {
                    "self": { "href": "/invoice/2" }
                },
                "id": 2,
                "total": 94.87,
                "no_items": 7
            }
        ]
    }
}

Now, assume we want to have an _embedded collection of resources inside each invoice resource to list the products ordered. I’m not aware of anywhere in the HAL spec that explicitly states nested embedded is valid HAL. Arguably, the diagram in the HAL specification by Mike Kelly suggests embedded resources are recursive. The major issue with not supporting nested embedded resources is the client consuming the API has to perform a lot of “round trips” to request each embedded resource individually via the resource href link. Take a look at the payload below illustrating nested embedded resources.

{
    "_links": {
        "self": { "href": "/invoices" }
    },
    "_embedded": {
        "invoices": [
            {
                "_links": {
                    "self": { "href": "/invoice/1" }
                },
                "_embedded": {
                    "items": [
                        { "_links": { "self": { "href": "/product/1" }}, "id": 1, "name": "Super cheap Macbook Pro", "price": 2.99 }
                    ]
                },
                "id": 1,
                "total": 2.99,
                "no_items": 1
            },
            {
                "_links": {
                    "self": { "href": "/invoice/2" }
                },
                "_embedded": {
                    "items": [
                        { "_links": { "self": { "href": "/product/2" }}, "id": 2, "name": "Raspberry Pi", "price": 34.87 },
                        { "_links": { "self": { "href": "/product/3" }}, "id": 3, "name": "Random product", "price": 30 },
                        { "_links": { "self": { "href": "/product/4" }}, "id": 4, "name": "More randomness", "price": 30 }
                    ]
                },
                "id": 2,
                "total": 94.87,
                "no_items": 3
            }
        ]
    }
}

Now we list each product item as an embedded resource in the already existing invoice resource. This is a great way of exposing the API for additional resources without having to make additional requests to retrieve the resources from the server. Imagine having to make a request for each embedded product inside the invoice resource – this would hammer the server and probably kill it when under heavy load.

So there we have it, nested embedded resources is indeed valid HAL and doesn’t break any of the conventions or spec set out in the rfc. I wanted to clarify this because there’s been a number of discussions where people aren’t sure whether nested embedded resources is officially valid HAL. To back this up, I asked Mike Kelly himself via Twitter;

https://twitter.com/mikekelly85/status/489105600685809664

Uglify Causing Issues in IE8

I’ve recently been working on a project that requires IE8 support (eek!). The application is a one page app, written in Backbone with Marionette using Grunt as a taskrunner. During the “grunt build” process, all Javascript files are concatenated, minified and uglified. Unfortunately, using Uglifies default configuration in the Gruntfile caused issues with some of the variable names, which, in turn, caused Internet Explorer 8 to barf with an error.

After looking through the Uglify documentation (https://github.com/mishoo/UglifyJS), I found an interesting option that exists under the –beautify option called –quote-keys. After putting the following config into the Gruntfile, IE8 magically worked. Or is it magic?…

uglify: {
    options: {
        preserveComments: false,
        compress : false,
        mangle : false,
        beautify : {
            beautify: false,
            ascii_only: true,
            quote_keys: true
        }
    }
}

The quote_keys option will “quote keys in literal objects”. Basically, this means variable names are wrapped in an object with name-value pairs i.e.

var myObject = {
    foo: foo,
    bar: bar
};

After adding the additional “quote_keys” option to the Gruntfile, IE8 worked as intended.

Zend Framework 2: Caching Using Event Manager

Caching is a great way of storing and returning data from a temporary store without having to do necessary business logic to fetch the data after it’s already been fetched once. Basically, the data is retrieved once and stored temporarily “somewhere”, whether, it be a file system, database, memory, for a specific amount of time. The next time the same page is loaded, the data has already been retrieved and can therefore be pulled out of temporary storage without having to do the computation all over again. This is particularly useful in applications that receive a lot of traffic, therefore, hammering the server with lots of requests.

Zend Framework 2 provides a number of ways to deal with caching out of the box via configuration. A handy concept is to catch a request through the MvcEvent::EVENT_ROUTE with a negative priority, check if what’s being requested exists in the cache. Should the item exist, return a response, otherwise, allow the application to continue and finish rendering via the controller. If the application reaches the controller, listen into the MvcEvent::EVENT_RENDER event and inject some data into the cache.

A friend of mine, Shenghua, has written a blog post about the implementation of how to use the ZF2 event manager to store and retrieve data from the cache. Check out his blog post https://github.com/shenghuahe/zf2-cache-mvc-response

Practical examples of design patterns in PHP

I’ve been doing a lot of reading into design patterns and currently half way through the Head First Design Patterns book. Firstly, I’d like to mention that the book is a great read and explains the patterns in such a way that it’s fairly simple to understand and grasp the concepts. The book explains how each pattern is implemented in Java, along with, class diagrams and great annotations.

As we all know, Java is an object oriented programming language and therefore, most of the same principles and structure can be applied in PHP. With this being said, I wanted to find some practical examples of how each pattern is implemented in PHP. Luckily, I found a great GitHub repository from Dominik Liebler that lists each pattern, from strategy to service locator to decorator – a lot of the common patterns are listed in this GitHub repository https://github.com/domnikl/DesignPatternsPHP

I found it particularly useful looking at the unit tests to see the entry point for each pattern and how the different objects interact with each other.