Responses

Phalcon REST is designed to work with Fractal’s Transformer concept to handle complex data output. Extending your custom controller from PhalconRest\Mvc\Controllers\FractalController provides you with several methods for creating different responses.

FractalController

createResponse()

By default createResponse takes $response as argument and returns it. Overriding this method allows you to modify the response before it will be send.

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function createResponse($response) {

        // For example
        if ($this->responseValid($response)) {
            return $response;
        }

        return null;
    }
}

createArrayResponse()

Let’s say you want to return just an array with data, for instance an array with your session token.

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function authenticate() {

        // Authentication code here

        // We've successfully created a session
        return $this->createArrayResponse([
            'token' => $session->getToken(),
            'expires' => $session->getExpirationTime()
        ]);
    }
}

Response:

{
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1c2VybmFtZSIsInN1YiI6IjEiLCJpYXQiOjE0NDk3NTY4MDAsImV4cCI6MjkwMDExODQwMH0.FE8VYcuh68fxqH17AjILWgcIrOkDp9Q6fBPneD_W4Rc",
    "expires": 1450361600
}

createOkResponse()

You might want to send just an OK response, for instance when you’ve successfully deleted something.

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function delete($id) {

        // Remove object code here
        return $this->createOkResponse();
    }
}

Response:

{
    "result": "OK"
}

createItemOkResponse()

Send ok along with item response

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function find($id) {

        return $this->createItemOkResponse($item, new ItemTransformer, 'item');
    }
}

Response:

{
    "result": "OK",
    "item": {
        // ..
    }
}

createItemResponse()

Creates a Fractal Item response

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function find($id) {

        return $this->createItemResponse($item, new ItemTransformer, 'item');
    }
}

Response:

{
    "item": {
        // ..
    }
}

createCollectionResponse()

Creates a Fractal Collection response

<?php

use PhalconRest\Mvc\Controllers\FractalController;

class CustomController extends FractalController
{
    public function all() {

        return $this->createCollectionResponse($items, new ItemTransformer, 'items');
    }
}

Response:

{
    "items": [{
        // ..
    }, {
        // ..
    }]
}