PHP code example of phossa2 / middleware

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

    

phossa2 / middleware example snippets


use Phossa2\Middleware\Queue;
use Zend\Diactoros\Response;
use Zend\Diactoros\ServerRequestFactory;

// create middleware queue
$mws = new Queue([
    new LoggerMiddleware(),
    new DispatcherMiddleware()
]);

// process the queue
$response = $mws->process(ServerRequestFactory::fromGlobals(), new Response());

$mws = (new Queue())
    ->push(new LoggerMiddleware())
    ->push(new DispatcherMiddleware());

  use Psr\Http\Message\RequestInterface;
  use Psr\Http\Message\ResponseInterface;

  function (
      RequestInterface $request,
      ResponseInterface $response,
      callable $next
  ) : ResponseInterface {
      // ...
  }
  

  // subqueue
  $subQueue = new Queue([
      new ResponseTimeMiddleware(),
      new LoggingMiddleware(),
      // ...
  ]);

  // main middleware queue
  $mws = new Queue([
      $subQueue,
      new DispatcherMiddleware(),
      // ...
  ]);

  $response = $mws->process(ServerRequestFactory::fromGlobals(), new Response());
  

  function (RequestInterface $request, ResponseInterface $response) : bool
  {
      // ...
  }
  

  // add condition during instantiation
  $mws = new Queue([
      [$subQueue, new DebugTurnedOnCondition()],
      new DispatcherMiddleware(),
  ]);

  // or during the push
  $mws->push(new AuthMiddleware(), new PathPrefixCondition('/user'));
  

  // use terminatable queue
  $tQueue = new TerminateQueue([...]);

  $mws = new Queue([
      [$tQueue, new SomeCondition()], // execute & terminate if condition true
      $mw2,
      $mw3,
      // ...
  ]);

  $response = $mws->process($request, $response);