PHP Classes

File: examples/case-studies/api/api_batch_orchestrator/api_batch_orchestrator.php

Recommend this page to a friend!
  Packages of Christos Drogidis   Ascoos OS   examples/case-studies/api/api_batch_orchestrator/api_batch_orchestrator.php   Download  
File: examples/case-studies/api/api_batch_orchestrator/api_batch_orchestrator.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Ascoos OS
A PHP Web 5.0 Kernel for decentralized web and IoT
Author: By
Last change: API Batch Orchestrator
Date: 6 months ago
Size: 7,237 bytes
 

Contents

Class file image Download
<?php
/**
 * @ASCOOS-NAME : Ascoos OS
 * @ASCOOS-VERSION : 26.0.0
 * @ASCOOS-SUPPORT : support@ascoos.com
 * @ASCOOS-BUGS : https://issues.ascoos.com
 *
 *
 * @CASE-STUDY : api_batch_orchestrator.php
 * @fileNo : ASCOOS-OS-CASESTUDY-SEC00013
 *
 * @desc <English> This case study demonstrates how Ascoos OS can be used to orchestrate multiple API requests with caching and event-driven logic.
 * @desc <Greek> ???? ? ?????? ?????????? ??????? ??? ?? Ascoos OS ?????? ?? ?????????????? ??? ??? ?????????? ????????? API ????????? ?? caching ??? ?????? ?????????.
 *
 * @since PHP 8.2.0+
 */
declare(strict_types=1);

use
ASCOOS\OS\Kernel\{
   
API\TAPIHandler,
   
Arrays\Events\TEventHandler
};
use function
ASCOOS\OS\Kernel\Cache\selectCache;

global
$AOS_CACHE_PATH, $AOS_LOGS_PATH;

// <English> Define configuration properties
// <Greek> ??????? ????????? ?????????
$properties = [
   
'cache' => [
       
'useCache' => true,
       
'cacheType' => 'file',
       
'cachePath' => $AOS_CACHE_PATH . '/' ,
       
'cacheDuration' => 3000
   
],
   
'logs' => [
       
'useLogger' => true,
       
'dir' => $AOS_LOGS_PATH .'/',
       
'file' => 'api_batch_orchestrator.log'
   
]
];

$options = [
   
'headers' => [
       
'Content-Type' => 'application/json'
   
],
   
'timeout' => 30
];

try {
   
// <English> Create an Event Handler for logging
    // <Greek> ?????????? ???????? ????????? ??? ?????????
   
$eventHandler = new TEventHandler([], $properties);
   
   
// <English> Register event for successful batch API request
    // <Greek> ??????? ????????? ??? ??????????? ?????? ?????? API
   
$eventHandler->register('module', 'api.batch.success', fn($data) => error_log("Batch Success: " . json_encode($data)));

   
// <English> Register event for failed batch API request
    // <Greek> ??????? ????????? ??? ??????????? ?????? ?????? API
   
$eventHandler->register('module', 'api.batch.failed', fn($data) => error_log("Batch Failed: " . json_encode($data)));

   
// <English> Initialize TCacheHandler for caching
    // <Greek> ???????????? ??? TCacheHandler ??? caching
   
$cacheHandler = selectCache(
       
cacheType: $properties['cache']['cacheType'], // <English> Cache type
                                                            // <Greek> ????? cache
       
cacheTime: $properties['cache']['cacheDuration'], // <English> Cache duration in seconds
                                                            // <Greek> ???????? cache ?? ????????????
       
properties: $properties, // <English> Cache directory
                                                            // <Greek> ????????? cache
       
cachePath: $properties['cache']['cachePath']
    );

   
// <English> Initialize TAPIHandler for the JSONPlaceholder API
    // <Greek> ???????????? ??? TAPIHandler ??? ?? JSONPlaceholder API
   
$api = new TAPIHandler(
       
url: 'https://jsonplaceholder.typicode.com', // <English> Base URL for the API
                                                        // <Greek> ?????? URL ??? ?? API
       
type: 0, // <English> Use TCurlHandler
                                                        // <Greek> ????? TCurlHandler
       
options: $options, // <English> Set headers and timeout
                                                        // <Greek> ??????? headers ??? ???????? ?????
       
properties:$properties, // <English> Cache settings
                                                        // <Greek> ????????? cache
   
);

   
// <English> Set the event handler
    // <Greek> ??????? ??? ???????? ?????????
   
$api->setEventHandler($eventHandler);

   
// <English> Define multiple endpoints for batch requests
    // <Greek> ??????? ????????? endpoints ??? ?????? ????????
   
$batchRequests = [
        [
'endpoint' => 'posts', 'params' => ['userId' => 1]], // <English> Fetch posts for user 1
                                                                    // <Greek> ???????? posts ??? ??? ?????? 1
       
['endpoint' => 'comments', 'params' => ['postId' => 1]], // <English> Fetch comments for post 1
                                                                    // <Greek> ???????? ??????? ??? ?? post 1
       
['endpoint' => 'users', 'params' => ['id' => 1]] // <English> Fetch user data
                                                                    // <Greek> ???????? ????????? ??????
   
];

   
// <English> Execute batch GET requests with caching
    // <Greek> ???????? ??????? GET ????????? ?? caching
   
$responses = [];
    foreach (
$batchRequests as $request) {
       
// <English> Generate cache key
        // ?????????? ???????? cache
       
$cacheKey = md5($request['endpoint'] . json_encode($request['params'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
       
       
// <English> Check if response is in cache
        // <Greek> ??????? ?? ? ???????? ??????? ???? cache
       
$cacheData = $cacheHandler->getCache($cacheKey);
        if (
$cacheData !== false) {
           
$responses[$request['endpoint']] = $cacheData;
        } else {
           
// <English> Execute GET request and cache response
            // <Greek> ???????? GET ????????? ??? ?????????? ???? cache
           
$response = $api->sendGetRequest("{$request['endpoint']}", $request['params']);
           
$cacheHandler->saveCache($cacheKey, $response);
           
$responses[$request['endpoint']] = $response;
        }
    }

   
// <English> Emit event for successful batch processing
    // <Greek> ??????? ????????? ??? ??????????? ?????? ???????????
   
$api->emit('api.batch.success', ['responses' => $responses]);

   
// <English> Display the responses
    // <Greek> ???????? ??? ??????????
   
print_r($responses);

   
// <English> Free resources
    // <Greek> ???????????? ?????
   
$api->Free();
   
$cacheHandler->Free();
   
$event->Free();

} catch (
InvalidArgumentException $e) {
   
// <English> Handle errors and emit failure event
    // <Greek> ????????? ????????? ??? ??????? ????????? ?????????
   
$api->emit('api.batch.failed', ['error' => $e->getMessage()]);
   
$api->Free();
    echo
'Error: ' . $e->getMessage();
}