PHP code example of yiisoft / middleware-dispatcher

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

    

yiisoft / middleware-dispatcher example snippets


use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
use Yiisoft\Middleware\Dispatcher\MiddlewareFactory;

$dispatcher = new MiddlewareDispatcher(
    new MiddlewareFactory($diContainer),
    $eventDispatcher
);

$dispatcher = $dispatcher->withMiddlewares([
    TeapotAccessChecker::class,
    static function (): ResponseInterface {
        return new Response(418);
    },
]);

  static function (): MiddlewareInterface {
      return new TestMiddleware();
  }
  

  [
      'class' => MyMiddleware::class,
      '__construct()' => [
          'someVar' => 42,
      ],
  ]
  

$request = new ServerRequest('GET', '/teapot');
$response = $dispatcher->dispatch($request, $this->getRequestHandler());

use \Psr\Http\Message\ServerRequestInterface;
use \Yiisoft\Middleware\Dispatcher\ParametersResolverInterface;

class CoolParametersResolver implements ParametersResolverInterface
{
    public function resolve(array $parameters, ServerRequestInterface $request): array
    {
        $resolvedParameters = [];
        foreach ($parameters as $name => $parameter) {
            if ($request->getAttribute($name) !== null) {
                $resolvedParameters[$name] = $request->getAttribute($name)
            }
        }
        
        return $resolvedParameters;
    }
}

use Psr\Container\ContainerInterface;
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
use Yiisoft\Middleware\Dispatcher\MiddlewareFactory;
use Yiisoft\Middleware\Dispatcher\ParametersResolverInterface;

/** 
 * @var ContainerInterface $container
 * @var ParametersResolverInterface $resolver
 * @var EventDispatcherInterface $eventDispatcher 
 */
$dispatcher = new MiddlewareDispatcher(new MiddlewareFactory($container, $resolver), $eventDispatcher);

use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Yiisoft\Middleware\Dispatcher\CompositeParametersResolver;
use Yiisoft\Middleware\Dispatcher\MiddlewareDispatcher;
use Yiisoft\Middleware\Dispatcher\MiddlewareFactory;
use Yiisoft\Middleware\Dispatcher\ParametersResolverInterface;

/** 
 * @var ContainerInterface $container
 * @var ParametersResolverInterface $resolver1
 * @var ParametersResolverInterface $resolver2
 * @var EventDispatcherInterface $eventDispatcher 
 */
$dispatcher = new MiddlewareDispatcher(
    new MiddlewareFactory($container, new CompositeParametersResolver($resolver1, $resolver2)), 
    $eventDispatcher,
);