PSR-15 ---Best Php training in trivandrum soddisfare technologes trivandrumm php training and 100 % placement in trivandrum
PSR-15
Caveat
Background
function (
ServerRequestInterface $request,
ResponseInterface $response,
callable $next
) : ResponseInterface
function (
ServerRequestInterface $request,
ResponseInterface $response
) : ResponseInterface
"Double Pass"
interface DelegateInterface
{
public function process(ServerRequestInterface $request) : ResponseInterface;
}
interface MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
DelegateInterface $delegate
) : ResponseInterface;
}
interface RequestHandlerInterface
{
public function handle(ServerRequestInterface $request) : ResponseInterface;
}
interface MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
) : ResponseInterface;
}
The final packages are now owned by the PHP-FIG group, however, and use the
Psr top-level namespace.The Interfaces
namespace Psr\Http\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
interface RequestHandlerInterface
{
public function handle(ServerRequestInterface $request) : ResponseInterface;
}
namespace Psr\Http\Server;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
interface MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
) : ResponseInterface;
}
How to write re-usable middleware
class CheckOriginMiddleware implements MiddlewareInterface
{
private $acceptedOrigins;
private $responsePrototype;
public function __construct(array $acceptedOrigins, ResponseInterface $responsePrototype)
{
$this->acceptedOrigins = $acceptedOrigins;
$this->responsePrototype = $responsePrototype;
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
{
$origin = $request->getHeaderLine('origin');
if (! in_array($origin, $this->acceptedOrigins, true)) {
return $this->responsePrototype
->withStatus(401)
->withHeader('X-Invalid-Origin', $origin);
}
$response = $handler->handle($request);
return $response->withHeader('X-Origin', $origin);
}
}
// Pipe it as a service to pull from the DI container:
$app->pipe(CheckOriginMiddleware::class);
// Use it within a route-specific pipeline:
$app->post('/api/foo', [
CheckOriginMiddleware::class,
FooMiddleware::class,
]);
$broker->always([CheckOriginMiddleware::class]);
$dispatcher = new Dispatcher([
/* ... */
new CheckOriginMiddleware($acceptedOrigins, $responsePrototype),
/* ... */
]);
Comments
Post a Comment