PHP code example of middlewares / utils

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

    

middlewares / utils example snippets


use Middlewares\Utils\Factory;
use Middlewares\Utils\FactoryDiscovery;

// Create PSR-7 instances
$request = Factory::createRequest('GET', '/');
$serverRequest = Factory::createServerRequest('GET', '/');
$response = Factory::createResponse(200);
$stream = Factory::createStream('Hello world');
$uri = Factory::createUri('http://example.com');
$uploadedFile = Factory::createUploadedFile($stream);

// Get PSR-17 instances (factories)
$requestFactory = Factory::getRequestFactory();
$serverRequestFactory = Factory::getServerRequestFactory();
$responseFactory = Factory::getResponseFactory();
$streamFactory = Factory::getStreamFactory();
$uriFactory = Factory::getUriFactory();
$uploadedFileFactory = Factory::getUploadedFileFactory();

// By default, use the FactoryDiscovery class that detects diactoros, guzzle, slim, nyholm and sunrise (in this order of priority),
// but you can change it and add other libraries

Factory::setFactory(new FactoryDiscovery(
    'MyApp\Psr17Factory',
    FactoryDiscovery::SLIM,
    FactoryDiscovery::GUZZLE,
    FactoryDiscovery::DIACTOROS
));

//And also register directly an initialized factory
Factory::getFactory()->setResponseFactory(new FooResponseFactory());

$fooResponse = Factory::createResponse();

use Middlewares\Utils\Dispatcher;

$response = Dispatcher::run([
    new Middleware1(),
    new Middleware2(),
    new Middleware3(),
    function ($request, $next) {
        $response = $next->handle($request);
        return $response->withHeader('X-Foo', 'Bar');
    }
]);

use Middlewares\Utils\CallableHandler;

$callable = new CallableHandler(function () {
    return 'Hello world';
});

$response = $callable();

echo $response->getBody(); //Hello world

use Middlewares\Utils\HttpErrorException;

try {
    $context = ['problem' => 'Something bad happened'];
    throw HttpErrorException::create(500, $context);
} catch (HttpErrorException $exception) {
    $context = $exception->getContext();
}