PHP code example of jerome / fetch-php

1. Go to this page and download the library: Download jerome/fetch-php 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/ */

    

jerome / fetch-php example snippets




use Fetch\Interfaces\Response as ResponseInterface;

$data = null;

// Asynchronously send a POST request using async/await syntax
async(fn () => fetch('https://example.com', [
    'method' => 'POST',
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode(['key' => 'value']),
]))
    ->then(fn (ResponseInterface $response) => $data = $response->json())  // Success handler
    ->catch(fn (\Throwable $e) => echo "Error: " . $e->getMessage());      // Error handler

// The async operation is managed with start, pause, resume, and cancel controls
$task = async(fn () => fetch('https://example.com', [
    'method' => 'POST',
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode(['key' => 'value']),
]));

// Manually control the task lifecycle as `then` and `catch` will automatically start the task
$task->start();

// Pause the task if needed
$task->pause();

// Resume the task
$task->resume();

// Cancel the task if 



use Matrix\Task;
use Matrix\Enum\TaskStatus;

// Define a long-running task
$task = new Task(function () {
    return "Task completed!";
});

// Start the task
$task->start();

// Pause and resume the task dynamically
$task->pause();
$task->resume();

// Cancel the task if needed
$task->cancel();

// Retry the task if it fails
if ($task->getStatus() === TaskStatus::FAILED) {
    $task->retry();
}

$result = $task->getResult();



$response = fetch('https://example.com', [
    'method' => 'POST',
    'headers' => [
        'Content-Type' => 'application/json',
    ],
    'body' => json_encode(['key' => 'value']),
]);

$data = $response->json();



use Fetch\Interfaces\Response as ResponseInterface;

$data = null;

// Asynchronously send a POST request using async/await syntax
async(fn () => fetch('https://example.com', [
    'method' => 'POST',
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode(['key' => 'value']),
]))
    ->then(fn (ResponseInterface $response) => $data = $response->json())  // Success handler
    ->catch(fn (\Throwable $e) => echo "Error: " . $e->getMessage());      // Error handler



$response = fetch()
    ->baseUri('https://example.com')
    ->withHeaders(['Content-Type' => 'application/json'])
    ->withBody(['key' => 'value'])
    ->withToken('fake-bearer-auth-token')
    ->post('/posts');

$data = $response->json();



use Fetch\Interfaces\Response as ResponseInterface;

$data = null;

// Asynchronously send a POST request using the fluent API
async(fn () => fetch()
    ->baseUri('https://example.com')
    ->withHeaders(['Content-Type' => 'application/json'])
    ->withBody(['key' => 'value'])
    ->withToken('fake-bearer-auth-token')
    ->post('/posts'))
    ->then(fn (ResponseInterface $response) => $data = $response->json())  // Success handler
    ->catch(fn (\Throwable $e) => echo "Error: " . $e->getMessage());      // Error handler



use Fetch\Http\ClientHandler;

$response = ClientHandler::handle('GET', 'https://example.com', [
    'headers' => ['Accept' => 'application/json']
]);

$data = $response->json();



use Fetch\Http\ClientHandler;

$data = null;

// Asynchronously manage a request using the ClientHandler
async(fn () => ClientHandler::handle('POST', 'https://example.com', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode(['key' => 'value']),
]))
    ->then(fn ($response) => $data = $response->json())
    ->catch(fn ($e) => echo "Error: " . $e->getMessage());



$response = fetch('https://nonexistent-url.com');

if ($response->ok()) {
    echo $response->json();
} else {
    echo "Error: " . $response->statusText();
}



$response = async(fn () => fetch('https://nonexistent-url.com'))
    ->then(fn ($response) => $response->json())
    ->catch(fn ($e) => echo "Error: " . $e->getMessage());

echo $response;



$response = async(fn () => fetch('https://api.example.com/resource'))
    ->then(fn ($response) => $response->json())
    ->catch(function (\Throwable $e) {
        // Implement retry logic with exponential backoff
        static $attempt = 1;
        if ($attempt <= 3) {
            sleep(pow(2, $attempt));  // Exponential backoff
            $attempt++;
            return retryRequest();  // Custom function to retry
        }
        return "Error: " . $e->getMessage();
    });

echo $response;



$response = fetch('https://example.com', [
    'proxy' => 'tcp://localhost:8080'
]);

// or

$response = fetch('https://example.com')
    ->withProxy('tcp://localhost:8080')
    ->get();

echo $response->statusText();



$response = fetch('https://example.com/secure-endpoint', [
    'auth' => ['username', 'password']
]);

// or

$response = fetch('https://example.com')
    ->baseUri('https://example.com/')
    ->withAuth('username', 'password')
    ->get('/secure-endpoint');

echo $response->statusText();
bash
composer