PHP code example of wimski / laravel-psr-http

1. Go to this page and download the library: Download wimski/laravel-psr-http 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/ */

    

wimski / laravel-psr-http example snippets




declare(strict_types=1);

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;

class TestCommand extends Command
{
    protected $signature = 'http:test';
    protected $description = 'Test the HTTP client';

    public function __construct(
        protected ClientInterface $httpClient,
        protected RequestFactoryInterface $requestFactory,
        protected StreamFactoryInterface $streamFactory,
    ) {
        parent::__construct();
    }

    public function handle(): void
    {
        $stream = $this->streamFactory->createStream(json_encode([
            'title'  => 'foo',
            'body'   => 'bar',
            'userId' => 1,
        ]));

        $request = $this->requestFactory->createRequest('POST', 'https://jsonplaceholder.typicode.com/posts')
            ->withHeader('Content-type', 'application/json; charset=UTF-8')
            ->withBody($stream);

        try {
            $response = $this->httpClient->sendRequest($request);
            dump(json_decode((string) $response->getBody(), true));
        } catch (ClientExceptionInterface $exception) {
            dump($exception->getMessage());
        }
    }
}