03
Jan '16

Controller Traits for JSON Responses

When building controllers I, along with many others I’m sure, generally create an abstract ‘base’ controller to contain some standard functionality, and which all the other controllers can extend. I use these for common pre/post processing functions, session management and all sorts of other stuff. This works well for a simple site, however there are many instances where controllers can’t all extend the same base class – for example if you want to setup shared CRUD functionality this will have to be different with normal vs nested resources. Where I have controllers that can’t all extend the same base class but still need to have some functionality in common I like to use a trait. A key example of this is when handling JSON responses I tend to use the following trait:

trait JSON {

    /**
     * Send success
     * @param string [$message='OK'] Message
     * @param integer [$response_code=200] Response code
     */
    protected function sendSuccess($message = 'OK', $response_code = 200) {
        return $this->sendResponse([], $message, $response_code);
    }

    /**
     * Send failure
     * @param string [$message='Error'] Message
     * @param integer [$response_code=404] Response code
     */
    protected function sendFailure($message = 'Error', $response_code = 404) {
        return $this->sendResponse([], $message, $response_code);
    }

    /**
     * Send error
     * @param array $data Data
     * @param string [$message='OK'] Message
     * @param integer [$response_code=200] Response code
     */
    protected function sendResponse($data, $message = 'OK', $response_code = 200) {
        $data = ['success' => ($response_code >= 200 && $response_code < 300), 'message' => $message, 'data' => $data];

        return response()->json($data, $response_code);
    }
}

This code is written for Laravel 5, but could easily be adapted to another framework.

Leave a Reply