PHP code example of windwalker / middleware

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

    

windwalker / middleware example snippets

 php
use Windwalker\Middleware\CallbackMiddleware;
use Windwalker\Middleware\AbstractMiddleware;

class TestA extends AbstractMiddleware
{
	/**
	 * call
	 *
	 * @return  mixed
	 */
	public function call()
	{
		echo ">>> AAAA\n";

		$this->next->call();

		echo "<<< AAAA\n";
	}
}

class TestB extends AbstractMiddleware
{
	/**
	 * call
	 *
	 * @return  mixed
	 */
	public function call()
	{
		echo ">>> BBBB\n";

		$this->next->call();

		echo "<<< BBBB\n";
	}
}

$a = new TestA;

$a->setNext(new TestB);

$a->call();
 php
$a = new TestA;
$b = new TestB;

$a->setNext($b);
$b->setNext(new CallbackMiddleware(
	function($next)
	{
		echo ">>>CCCC\n";
		echo "<<<CCCC\n";
	}
));

$a->call();
 php
$ware = new CallbackMiddleware(
	function($next)
	{
		echo ">>>CCCC\n";

		$next->call();

		echo "<<<CCCC\n";
	},
	new NextMiddleware
)
 php
class TestB extends Middleware
{
	/**
	 * call
	 *
	 * @return  mixed
	 */
	public function call()
	{
		echo ">>> BBBB\n";

		$this->next->call();

		echo "<<< BBBB\n";
	}
}

$b = new TestB;

$b->call();

// Error, next not exists.
 php
$b = new TestB;

$b->setNext(new EndMiddleware);

$b->call();
 php
use Windwalker\Middleware\Chain\ChainBuilder;

$chain = new ChainBuilder;

$chain
    ->add('TestA')
    ->add(new TestB)
    ->add(function($next)
    {
        echo ">>>CCCC\n";
        echo "<<<CCCC\n";
    });

$chain->call();
 php
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Windwalker\Middleware\Chain\Psr7ChainBuilder;
use Windwalker\Middleware\Psr7Middleware;

class MyPsr7Middleware implements \Windwalker\Middleware\Psr7InvokableInterface
{
	public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next = null)
	{
		// Do something

		$result = $next($request, $response);

		// Do something

		return $result;
	}
}

$mid = new Psr7Middleware(function (ServerRequestInterface $request, ResponseInterface $response, $next = null)
{
	// Do something
});

$chain = new Psr7ChainBuilder;
$chain->add(new MyPsr7Middleware)
	->add($mid);

$chain->execute(new ServerRequest, new Response);