PHP code example of affinity4 / middleware-factory

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

    

affinity4 / middleware-factory example snippets


use Affinity4\MiddlewareFactory\Factory;

$request = Factory::createServerRequest('GET', '/');
$response = Factory::createResponse(200);
$stream = Factory::createStream('Hello world');
$uri = Factory::createUri('http://example.com');

// By default MiddlewareFactory uses Nyholm\Psr7\Factory\Psr17Factory,
// but you can change it and add other classes
use Acme\Psr17Factory as AcmePsr17Factory
Factory::setStrategies([
    AcmePsr17Factory::class
]);

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

$fooResponse = Factory::createResponse();

// Get the PSR-17 factory used
$uriFactory = Factory::getUriFactory();
$uri = $uriFactory->createUri('http://hello-world.com');

use Affinity4\MiddlewareFactory\Dispatcher;

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

use Affinity4\MiddlewareFactory\CallableHandler;

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

$response = $callable();

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

use Affinity4\MiddlewareFactory\HttpErrorException;

$exception = HttpErrorException::create(500, [
    'problem' => 'Something bad happened',
]);

// Additional context can be get and set on the exception
$context = $exception->getContext();