protected function execute(array $args, Response $response) : mixed

Fires to execute the API event.


Description

This is the action that the event should perform when the authenticated user requested its execution.

The returned value will be used as output. In case the returned value is an array or an object, it will be automatically encoded in JSON format.

It is possible to throw an exception to safely abort the event execution.

This method should not contain any exit or die function, otherwise the event won't be properly terminated.


Parameters

$args

(array)  The provided arguments for the event, fetched from the JSON payload or from the args[] term set in query string.

$response

(Response)  The response object used to instruct the API system about the output mode. This class is part of the E4J\VikRestaurants\API namespace.

Return Value

Mixed. The response to output to the caller.


Example

The example below is used to load the details of a record (with matching ID) from a given database table.

/**
 * @inheritDoc
 * 
 * IMPORTANT: you first need to load the E4J\VikRestaurants\API\Response object accordingly.
 */
protected function execute(array $args, Response $response)
{
    // extract model from payload
    if (empty($args['model']))
    {
        // missing model
        $error = new Exception('Model not specified', 400);

        // register response and abort request
        $response->setStatus(0)->setContent($error->getMessage());

        throw $error;
    }

    // let's load the model
    $model = JModelVRE::getInstance($args['model']);

    if (!$model)
    {
        // the given model doesn't exist
        $error = new Exception(sprintf('Model [%s] does not exist', $args['model']), 404);

        // register response and abort request
        $response->setStatus(0)->setContent($error->getMessage());

        throw $error;
    }

    if (empty($args['id']))
    {
        // missing ID attribute
        $error = new Exception('The payload didn\'t specify the ID of the record', 400);

        // register response and abort request
        $response->setStatus(0)->setContent($error->getMessage());

        throw $error;
    }

    // fetch the details of the record
    $item = $model->getItem($args['id']);

    if (!$item)
    {
        // item not found
        $error = new Exception('The searched item does not exist', 404);

        // register response and abort request
        $response->setStatus(0)->setContent($error->getMessage());

        throw $error;
    }

    // item found, register successful response
    $response->setStatus(1);
    // register a short description for the administrator
    $response->setContent(sprintf('Fetched [%s] with ID [%s]', $args['model'], $args['id']));

    // lets the application framework safely outputs the response in JSON format
    return $item;
}

Useful Hints

The response of the request uses by default an application/json content type. For this reason, the value returned by the event is always encoded in JSON format, unless it is already a string. This means that, if we terminate an event with the following code:

return ['a' => 1, 'b' => 2];

The client that performed the request will receive this JSON as response:

{
    "a": 1,
    "b": 2
}

If you wish to use a different content type, in example to download a PDF, you can change the content type by calling:
$response->setContentType($type)

The example below explains how to start the download of an invoice.

// load invoice details
$invoice = JModelVRE::getModel('invoice')->getInvoice($id);
// read PDF bytes
$pdf = file_get_contents($invoice->path);
// overwrite content type
$response->setContentType('application/pdf');
// prepare additional headers
$app = JFactory::getApplication();
$app->setHeader('Content-Disposition', 'attachment; filename=' . basename($invoice->path));
$app->setHeader('Content-Length', strlen($pdf));
// return PDF bytes to start the download
return $pdf;

The event class is also able to track some environment variables, which are specifically stored for the relation between the executed event and the logged-in user.

The following example is used to track how many times the event has been executed by the currently logged in user.

// load the total number of executions
$counter = $this->get('counter', 0);
// increase counter by one and commit the update
$this->set('counter', ++$counter);
Last Update: 2023-12-29 14:15
Helpful?