Responses

This class allows you to output information back to the UI that made the API call. You can configure response code, output validation results, success messages, datatables results, json results, and error messages.

Examples

Here are examples of how to output your responses.

//This is how you include the response class.
use SlenderApi\Lib\Response\Response;

//Add this to use the Error Generator class.
use SlenderApi\Lib\Response\ErrorGenerator;

private Response $response;
public function __construct(object $controller)
{
    $this->response = $controller->response;
}

//These 3 methods contain all your configurable error messages.
//Lib/Response/ErrorGenerator/getValidationErrors()
getSystemErrors(), getValidationErrors(), getDataErrors()

//This method will return the error below:
//'27' => array('code' => 27, 'title' => 'User', 'detail' => 'Cannot register a user with an ID.'),
$error = ErrorGenerator::getError(27, 'users', 'data');

//This will add the error to your response object.
//You can add multiple errors and return all of them if you want.
$this->response->addError($error);

//This will output your errors and stop the code from continuing.
$this->response->dieWithCode(400);

//This is the same as dieWithCode but you can pass the errors directly to it.
//It will also stop the code from continuing.
$this->response->outputResponse(400, null, $errors);

//This will output a custom response without killing the code.
$this->response->echoResponse('{"success": true}');

//This will add data to your response.
//you can call it multiple times to add multiple items to your response.
$this->response->addData('user', $users[0]);

//This will log the user our of the API.
$this->response->clearCookiesWithCode(401);