PHP code example of echo-fusion / middlewaremanager

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

    

echo-fusion / middlewaremanager example snippets


use Psr\Http\Message\ResponseFactoryInterface
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

class MyMiddlewareHandler implements RequestHandlerInterface {
    public function __construct(private readonly ResponseFactoryInterface $responseFactory)
    {
    }

    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        // write your code here
        
        return $this->responseFactory->createResponse();
    }
}

use EchoFusion\MiddlewareManager\MiddlewareManager;
use EchoFusion\MiddlewareManager\MiddlewarePipeline;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

class CoreMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // ex: manipulate request
        $request = $request->withAttribute('key','value');
        
        return $handler->handle($request);
    }
}

class OtherMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response =  $handler->handle($request);
        
        // ex: manipulate response
        return $this->convertedResponse($response);
    }
}


use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use EchoFusion\MiddlewareManager\MiddlewarePipelineInterface;

function (ContainerInterface $container, ServerRequestInterface $request, MiddlewarePipelineInterface $pipeline) {

    // optional
    $coreMiddlewares = [
        CoreMiddleware::class,
    ];
    
    $middlewareManager = new MiddlewareManager(
        $container, 
        $pipeline, 
        $coreMiddlewares
    );
    
    // add or remove your necessary middlewares if you want
    $middlewareManager->add(OtherMiddleware::class);
    $middlewareManager->remove(OtherMiddleware::class);
    // ...
    
    // instantiate handler directly or get from container to resolve possible dependencies
    $handler = new MyMiddlewareHandler();
    
    $response = $middlewareManager->dispatch($request, $handler);
    
    echo $response;
}
bash
composer