Backend Controller

Mayd provides a base BackendController, that can be extended from in any of your backend controllers. It provides helpers for common actions:

Receiving a JSON Payload

When receiving data as JSON, you can use the JsonControllerTrait:

useMayd\Foundation\Controller\BackendController;
use Symfony\Component\HttpFoundation\Request;

class MyController extends BackendController
{
    public function someAction (Request $request) : Response
    {
        $data = $this->getJsonRequestData($request);
    }
}

The trait reads the request body and returns the json data. It will throw proper exceptions (to indicate a HTTP status code 4xx).

The method will only allow a nested JSON data structure, like an array or a key-value map. Scalars are not supported and will return an error 400.

Sending JSON

There are also convenience helpers for sending JSON, that are especially important if you are interacting with the BackendFetch client, as it relies on the given data structure.

class MyController extends BackendController
{
    public function someAction (Request $request) : Response
    {
        return $this->ajaxResponse(true, "ok")
            ->setData([
                "some data" => "here",
            ])
            ->build();
    }
}

The ->ajaxResponse() method is just a wrapper that creates a new AjaxResponseBuilder. Look at its public interface, to see all features (eg. automatically displaying a toast message).

AJAX Data Format

The following describe the details of the simple AJAX data format, that is used by the BackendFetch JS client and the AJAX response builder. You probably will never need to use this format directly, so it is just here for technical documentation and background.

The format is rather simple:

{
    ok: boolean,
    status: string,
    data?: {},
    redirect?: string,
    message?: string,
    messageType?: string,
    messageAction?: {
        label: string,
        action: string,
    },
}
parameters
nametypedescription
okboolA boolean indicating whether the response was a success
statusstringA status string that indicates the status of response (on top of ok)
dataany?The payload that is returned.
redirectstring?If set, the page will redirect to this URL.
messagestring?A toast message.
messageTypestring?The type of message neutral / positive / negative. Only useful in combination with message. By default neutral.
messageActionobject?An optional action button inside the message toast. Contains label as text and action as the target URL.

The BackendFetch automates a lot of the interaction, for example the message is automatically displayed as toast. The caller of the request will only receive {data, status, ok}, the rest is handled internally.