PHP code example of componenta / http-respond-interceptor
1. Go to this page and download the library: Download componenta/http-respond-interceptor 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/ */
componenta / http-respond-interceptor example snippets
use Componenta\Interceptor\Http\Attribute\Respond;
final class HealthController
{
#[Respond(200, 'application/json')]
public function __invoke(): array
{
return ['status' => 'ok'];
}
}
use Closure;
use Psr\Http\Message\ResponseInterface;
#[Respond(
200,
'application/json',
factory: static function (Closure $respond, mixed $result): ResponseInterface {
return $respond()
->withStatus(202)
->withHeader('X-Response-Source', 'factory');
},
)]
public function show(): array {}
final class UserController
{
#[Respond(200, factory: self::decorate(...))]
public function show(): array
{
return [];
}
private static function decorate(Closure $respond, mixed $result): ResponseInterface
{
return $respond()->withHeader('Cache-Control', 'no-store');
}
}
use Closure;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\SerializerInterface;
#[Respond(
200,
factory: static function (
Closure $respond,
mixed $result,
SerializerInterface $serializer,
): ResponseInterface {
return $respond($serializer->serialize($result, 'json'))
->withHeader('X-Response-Source', 'serialized-factory');
},
)]
public function show(): object {}
use Componenta\Interceptor\Http\Attribute\Created;
use Componenta\Interceptor\Http\Attribute\Respond;
#[Created]
public function create(): array {}
#[Respond(204)]
public function delete(): null {}
#[Respond(
200,
'application/json',
headers: [
'Cache-Control' => 'no-store',
'Vary' => ['Accept', 'Authorization'],
],
)]
public function show(): array {}
#[Created(headers: ['Location' => '/users/42'])]
public function create(): array {}