PHP code example of ascetic-soft / psr7

1. Go to this page and download the library: Download ascetic-soft/psr7 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/ */

    

ascetic-soft / psr7 example snippets


use AsceticSoft\Psr7\HttpFactory;

$factory = new HttpFactory();

// Create a response
$response = $factory->createResponse(200);
$response->getBody()->write('Hello, World!');

// Create a request
$request = $factory->createRequest('GET', 'https://example.com/api/users');

// Create a URI
$uri = $factory->createUri('https://example.com/path?query=1#fragment');

use AsceticSoft\Psr7\Request;
use AsceticSoft\Psr7\Response;
use AsceticSoft\Psr7\ServerRequest;
use AsceticSoft\Psr7\Stream;
use AsceticSoft\Psr7\Uri;

// Request
$request = new Request('POST', 'https://api.example.com/users', [
    'Content-Type' => 'application/json',
    'Authorization' => 'Bearer token123',
], Stream::create(json_encode(['name' => 'John'])));

// Response
$response = new Response(200, ['Content-Type' => 'text/html']);

// Server Request
$serverRequest = new ServerRequest('GET', '/api/users', serverParams: $_SERVER);

// URI
$uri = new Uri('https://example.com:8080/path?q=1#frag');
echo $uri->getHost();   // "example.com"
echo $uri->getPort();   // 8080
echo $uri->getPath();   // "/path"

use AsceticSoft\Psr7\HttpFactory;

$factory = new HttpFactory();

// RequestFactoryInterface
$request = $factory->createRequest('GET', '/path');

// ResponseFactoryInterface
$response = $factory->createResponse(404, 'Not Found');

// ServerRequestFactoryInterface
$serverRequest = $factory->createServerRequest('POST', '/api', $_SERVER);

// StreamFactoryInterface
$stream = $factory->createStream('content');
$fileStream = $factory->createStreamFromFile('/path/to/file', 'r');

// UriFactoryInterface
$uri = $factory->createUri('https://example.com');

// UploadedFileFactoryInterface
$uploadedFile = $factory->createUploadedFile($stream, 1024, UPLOAD_ERR_OK, 'file.txt');

use AsceticSoft\Psr7\ServerRequestCreator;

// Create from PHP superglobals ($_SERVER, $_GET, $_POST, $_COOKIE, $_FILES)
$request = ServerRequestCreator::fromGlobals();

// Or pass custom arrays
$request = ServerRequestCreator::fromGlobals(
    server: $_SERVER,
    get: $_GET,
    post: $_POST,
    cookies: $_COOKIE,
    files: $_FILES,
);

use AsceticSoft\Psr7\ServerRequestCreator;
use AsceticSoft\Waypoint\Router;

$router = new Router($container);

$router->get('/hello/{name}', function (string $name) use ($factory) {
    $response = $factory->createResponse();
    $response->getBody()->write("Hello, {$name}!");
    return $response;
});

$request = ServerRequestCreator::fromGlobals();
$response = $router->handle($request);