PHP code example of psg / psr-101

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

    

psg / psr-101 example snippets


use Psg\Psr100\Factory\Psr100Factory;
use Psg\Http\Message\{ResponseInterface, ServerRequestInterface};
use Psg\Http\Server\{MiddlewareAppInterface, MiddlewareInterface, MiddlewareNextInterface};


class App extends Psr100Factory implements MiddlewareAppInterface{
	public $middleware;
	public function __construct(){
		$this->middleware = new \SplObjectStorage();
	}
	public function handle(\Psr\Http\Message\ServerRequestInterface $request): ResponseInterface {
		$middleware = $this->middleware->current();
		$this->middleware->next();
		return $middleware->process($request, $this);
	}
	public function add($middleware){
		$this->middleware->attach($middleware);
	}
	public function remove($middleware){
		$this->middleware->detach($middleware);
	}
	public function has($middleware){
		return $this->middleware->contains($middleware);
	}
}

class Control implements MiddlewareInterface {
	public function process(ServerRequestInterface $request, MiddlewareAppInterface $app): ResponseInterface {
		return $app->createResponse(200)->withBody($app->createStream('there is one name in programming, and that name is bill'));
	}
}
class MiddleOut implements MiddlewareInterface {
	public function process(ServerRequestInterface $request, MiddlewareAppInterface $app): ResponseInterface {
		$response = $app->handle($request);
		$only_bob = preg_replace('/bill/i', 'bob', (string)$response->getbody());
		$new_stream = $response->getBody()->create($only_bob);
		return $response->withBody($new_stream);
	}
}

$App = new App;
$App->add(new MiddleOut);
$App->add(new Control);
$App->middleware->rewind();
$response = $App->handle($App->createServerRequest('get', 'http://bobery.com/'));
echo (string)$response->getBody();

#> there is one name in programming, and that name is bob