PHP Guide

Contents

  1. Prerequisites
  2. Download and import
  3. Attributes of a response
  4. Using pre-defined responses
  5. Encoding responses to JSON format
  6. More pre-defined responses
  7. Including data in responses
  8. Using custom classes in responses
  9. Adding lists
  10. Creating custom responses
  11. Decoding JSON text into Response objects

Prerequisites
  • PHP 7+
Download and import

To begin, download the Responz library for PHP.

Extract the folder 'Responz' from the downloaded ZIP file to the root of your code directory. You can then import the Responz library in your code using:

require_once("Responz\Responz.php");

Attributes of a response

All responses contain four internal attributes, inherited from a base class called Response. These are:

  • status - is either "ok" or "error" and is used to indicate the result of the request.
  • title - contains a title that very briefly describes the result of the request.
  • message - contains a message to the client describing the result in more detail.
  • timestamp - timestamp that indicates the time the request was processed.
  • data - (Optional) contains data returned related to the client's request. The data object will be omitted from any serialized JSON if it is not defined.

Using pre-defined responses

The library offers two existing responses that extend the Response base class by implicitly specifying the status. These are the SuccessResponse, which indicates that the user's request has been executed successfully (status = ok) and ErrorResponse, which indicates that an error occured when trying the execute the request (status = error). The following example shows how to instantiate a simple response, a Success response and an Error response.

$response1 = new Response(ResponseStatus::OK, "Response 1", "This is my first response", null);

//A successful response:
$successResponse = new SuccessResponse("Success", "This is a success response.", null);

//An error response:
$errorResponse = new ErrorResponse("Error", "This is an error response.", null);

Encoding responses to JSON format

You can encode a Response object into a JSON string using the toJSON() method:

$jsonText = $response1->toJSON();

This should produce the following JSON text:

{"status":"OK","title":"Response 1","message":"This is my first response","datetime":"2019-07-28 00:20:29"}
More pre-defined responses

There are some additional Response classes you can use. These are based on common responses that can be found in a large variety of projects.

  • InvalidParameterResponse - Commonly used when an invalid parameter is submitted in the request. For example, an integer was expected, but a string was found.
  • MissingParameterResponse - Commonly used when a parameter was expected but not provided.
  • SecurityResponse - Commonly used when a user makes a request that requires authentication/authorization and is denied access.
  • UnknownFailureResponse - Commonly used when something has gone wrong on the server side. This is usually used in conjunction with exceptions or other fault-dealing mechanisms.

For more information about pre-defined responses, check out the Documentation.

$invalidParameterResponse = new InvalidParameterResponse("myParam", "An integer, found string.", null);

$missingParameterResponse = new MissingParameterResponse("myParam", null);

$securityResponse = new SecurityResponse(null);

$unknownFailureResponse = new UnknownFailureResponse("A failure has occurred, please contact the administrator.", null);

Including data in responses

Each response has a data member which allows insertion of an arbitrary number of other objects. This member is initially null and will therefore not be printed in any encoded JSON text.

Creating data objects:

You can add raw data (Strings, Characters, Numbers and Booleans) using the array subscript operator:

$dataObject1["myIntValue"] = 10;
$dataObject1["myStringValue"] = "Hello!";

The array subscript operator also allows you to nest objects inside the data object (or any other object):

$nestedObject["nestedIntValue"] = -5;
$nestedObject["nestedBooleanValue"] = true;
//Nesting an object inside the data object etc.:
$dataObject1["myNestedObject"] = $nestedObject;

To set the data of the response in the constructor use:

$responseWithData = new SuccessResponse("Data response", "This is a response containing data.", $dataObject1);

Alternatively, you can set the data of a response after initialization using the setData() method:

$responseWithData->setData($dataObject1);
Using custom classes in responses

You can also define your own classes, which need to extend EasyJSON's JsonObject class:

use EasyJSON\JsonObject as JsonObject;

//Custom class example:
class Person extends JsonObject { //All used classes should extend the JsonObject class

    private $firstName;
    private $lastName;
    private $age;

    /**
     * Person constructor.
     * @param $firstName
     * @param $lastName
     * @param $age
     */
    public function __construct($firstName, $lastName, $age) {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->age = $age;
    }

    /**
     * @return mixed
     */
    public function getFirstName() {
        return $this->firstName;
    }

    /**
     * @param mixed $firstName
     */
    public function setFirstName($firstName) {
        $this->firstName = $firstName;
    }

    /**
     * @return mixed
     */
    public function getLastName() {
        return $this->lastName;
    }

    /**
     * @param mixed $lastName
     */
    public function setLastName($lastName) {
        $this->lastName = $lastName;
    }

    /**
     * @return mixed
     */
    public function getAge() {
        return $this->age;
    }

    /**
     * @param mixed $age
     */
    public function setAge($age) {
        $this->age = $age;
    }

}

If your class is on a different file, you need to import it using:

require_once("Person.php"); //Import your custom class

To include an instance of your class in a response, create an object and then use the toJsonObject() method when assigning it to a data object:

require_once("Person.php"); //Import your custom class
$person = new Person("John", "Doe", 50); //Instantiate a custom class object
$dataObject3["person"] = $person->toJsonObject();
$responseWithCustomObject = new SuccessResponse("Custom object response", "This is a response containing a custom object.", $dataObject3);

Adding lists

You can also add lists by defining a data object as an array and putting items in the array using the array_push() method:

$dataObject4["persons"] = array(); //Create a new data object as an array;

//Create 5 new people and add them in the array:
for ($i = 0; $i < 5; $i++) {
    $person = new Person("Firstname " . $i, "Lastname " . $i, $i + 30);
    array_push($dataObject4["persons"], $person->toJsonObject());
}

$responseWithCustomObject->setData($dataObject4); //Set the dataObject4 (the one including the array) as the data of the existing response:

Creating custom responses

You can create your own custom response by extending the Response, SuccessResponse or ErrorResponse classes:

class CustomResponse extends SuccessResponse { //This is custom response that returns "Hello World!" as a message:

    const MESSAGE = "Hello world!";

    public function __construct($data) {
        parent::__construct("Hello World!", "Custom response says Hello World!", $data);
    }

}

//Using the custom response:
$customResponse = new CustomResponse(null);

Decoding JSON text

You can decode JSON formatted text using PHP's native json_decode method:

$jsonText = $customResponse->toJSON(); //this contains the serialized/encoded JSON text
$object = json_decode($jsonText);

You can then get the values of statuses, titles, messages, date-time and data properties using:

echo "Status -> " . $object->status . PHP_EOL;
echo "Title -> " . $object->title . PHP_EOL;
echo "Message -> " . $object->message . PHP_EOL;
echo "Date/Time -> " . $object->datetime . PHP_EOL;

//Decode the data:
$data = $object->data;
echo "Data[myIntValue] -> " . $data->myIntValue . PHP_EOL;