PHP code example of arandu / reducible

1. Go to this page and download the library: Download arandu/reducible library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

arandu / reducible example snippets


use Arandu\Reducible\Reducible;

class MyClass
{
    use Reducible;

    public function callApi($url, $options)
    {
        // will call all reducers for the method name
        $options = $this->transformCallApiOptions($options);

        // ...
    }
}

// -----

// Register a 'transformCallApiOptions' reducer
MyClass::reducer('transformCallApiOptions', function ($options) {
    return [
        ...$options,
        'headers' => [
            ...($options['headers'] ?? []),
            'Authorization' => 'Bearer ' . $this->token,
        ],
    ];
});

// Multiple reducers can be added
MyClass::reducer('transformCallApiOptions', function ($options) {
    return [
        ...$options,
        'headers' => [
            ...($options['headers'] ?? []),
            'X-Api-Key' => $this->apiKey,
        ],
    ];
});

// -----

$myClass = new MyClass();

$myClass->callApi('https://api.example.com', [
    'headers' => [
        'Content-Type' => 'application/json',
    ],
]);
// The callApi method will be called with the following options:
// [
//     'headers' => [
//         'Content-Type' => 'application/json',
//         'Authorization' => 'Bearer ' . $myClass->token,
//         'X-Api-Key' => $myClass->apiKey,
//     ],
// ]