PHP code example of jacksonsr451 / php-easy-http

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

    

jacksonsr451 / php-easy-http example snippets




use PhpEasyHttp\Http\Server\Application;

n () => ['message' => 'pong']);

$app->post('/items/{id}', function (int $id, array $body) {
	return [
		'id' => $id,
		'payload' => $body,
	];
});

$app->run();

$app->put('/users/{userId}', function (int $userId, array $body) {
	return ['userId' => $userId, 'changes' => $body];
}, options: [
	'name' => 'users.update',
	'middleware' => ['auth'],
	'summary' => 'Update a user profile',
	'tags' => ['users'],
]);

use App\Controllers\UserController;
use PhpEasyHttp\Http\Server\Application;

$app = new Application();

/**
 * @RoutePrefix /api
 */
final class UserController
{
	/**
	 * @Route GET /users/{id}
	 * @Summary Fetch a single user
	 * @Tags users,read
	 * @Middleware auth
	 */
	public function show(int $id): array
	{
		return ['id' => $id];
	}
}

$app->registerControllers(UserController::class);

use App\Controllers\AdminController;
use PhpEasyHttp\Http\Server\Application;
use PhpEasyHttp\Http\Server\Support\Attributes\Route;
use PhpEasyHttp\Http\Server\Support\Attributes\RoutePrefix;

$app = new Application();

#[RoutePrefix('/admin')]
final class AdminController
{
	#[Route(method: ['GET', 'POST'], path: '/reports', middleware: ['auth'], summary: 'Reports', tags: ['reports'])]
	public function reports(): array
	{
		return ['reports' => []];
	}
}

$app->registerControllers(AdminController::class);

use Jacksonsr45\ApiGateway\Gateway;
use Jacksonsr45\ApiGateway\Loader\FileGatewayRouteSource;
use PhpEasyHttp\Http\Server\Application;

$app = new Application();
$gateway = new Gateway($app);

$gateway->addSource(new FileGatewayRouteSource(__DIR__ . '/routes/gateway.yaml'));
$gateway->boot();

$app->run();

use Psr\Log\LoggerInterface;

$app->register(LoggerInterface::class, fn () => new Monolog\Logger('api'));

$app->get('/secure', function (LoggerInterface $logger) {
	$logger->info('secure endpoint accessed');
	return ['ok' => true];
});

use PhpEasyHttp\Http\Server\Middleware;
use PhpEasyHttp\Http\Server\Interfaces\RequestHandlerInterface;
use PhpEasyHttp\Http\Message\Interfaces\ServerRequestInterface;

final class AuthMiddleware extends Middleware
{
	public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
	{
		if (!$request->getAttribute('user')) {
			return (new ResponseFactory())->json(['error' => 'Unauthorized'], 401);
		}

		return $handler->handle($request);
	}
}

$app->registerMiddleware('auth', AuthMiddleware::class);
$app->use('auth');                // global middleware
$app->get('/private', fn () => ['secret' => true]);
$app->get('/public', fn () => ['hello' => 'world'], options: ['middleware' => []]);

use PhpEasyHttp\Http\Server\Support\ResponseFactory;

$app->get('/download', function (ResponseFactory $responses) {
	return $responses->text('custom body', 202, ['X-Trace' => 'abc']);
});

$response = $app->run(emit: false);

// Assert, inspect, or emit manually
$app->emit($response);

use PhpEasyHttp\Http\Message\ServerRequest;
use PhpEasyHttp\Http\Message\Uri;

$request = new ServerRequest('GET', new Uri('http://localhost/ping'));
$response = $app->run($request, emit: false);

$this->assertSame(200, $response->getStatusCode());
$this->assertSame('{"message":"pong"}', (string) $response->getBody());