PHP code example of cormy / onion

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

    

cormy / onion example snippets


use Cormy\Server\Onion;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

// create the core of the onion, i.e. the innermost request handler
$core = function (ServerRequestInterface $request):ResponseInterface {
    return new \Zend\Diactoros\Response();
};

// create some scales (aka middlewares) to wrap around the core
$scales = [];

$scales[] = function (ServerRequestInterface $request):\Generator {
    // delegate $request to the next request handler, i.e. $core
    $response = (yield $request);

    return $response->withHeader('content-type', 'application/json; charset=utf-8');
};

$scales[] = function (ServerRequestInterface $request):\Generator {
    // delegate $request to the next request handler, i.e. the middleware right above
    $response = (yield $request);

    return $response->withHeader('X-PoweredBy', 'Unicorns');
};

// create an onion style middleware stack
$middlewareStack = new Onion($core, ...$scales);

// and process an incoming server request
$response = $middlewareStack(new \Zend\Diactoros\ServerRequest());

/**
 * Constructs an onion style PSR-7 middleware stack.
 *
 * @param RequestHandlerInterface|callable                         $core   the innermost request handler
 * @param (MiddlewareInterface|RequestHandlerInterface|callable)[] $scales the middlewares to wrap around the core
 */
public function __construct(callable $core, callable ...$scales)

/**
 * Process an incoming server request and return the response.
 *
 * @param ServerRequestInterface $request
 *
 * @return ResponseInterface
 */
public function __invoke(ServerRequestInterface $request):ResponseInterface