PHP code example of activecollab / middlewarestack

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

    

activecollab / middlewarestack example snippets


$stack = new MiddlewareStack();

$stack->addMiddleware(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
   // Route request to the contraoller, execute action, and encode action result to response

   if ($next) {
       $response = $next($request, $response);
   }
   
   return $response;
});

$stack->addMiddleware(function (ServerRequestInterface $request, ResponseInterface $response, callable $next = null) {
   if (!user_is_authenticated($request)) {
       return $response->withStatus(403); // Break here if user is not authenticated
   }

   if ($next) {
       $response = $next($request, $response);
   }
   
   return $response;
});

$request = new ServerRequest();
$response = $stack->process($request, new Response());

$stack->setExceptionHandler(function (Exception $e, ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(500, 'Exception: ' . $e->getMessage());

    return $response;
});

$stack->setPhpErrorHandler(function (Throwable $e, ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(500, 'PHP error: ' . $e->getMessage());

    return $response;
});