### Utopia HTTP Server Setup and Middleware Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Provides a comprehensive example of setting up a Utopia HTTP server, including global and group-specific initialization (`Http::init`) and shutdown (`Http::shutdown`) hooks for middleware execution. ```php use Utopia\Http\Http; use Utopia\Http\Swoole\Request; use Utopia\Http\Swoole\Response; use Swoole\Http\Server; use Swoole\Http\Request as SwooleRequest; use Swoole\Http\Response as SwooleResponse; use Utopia\Http\Validator\Wildcard; $http = new Server("0.0.0.0", 8080); Http::init(function($response) { /* Example of global init method. Do stuff that is common to all your endpoints in all groups. This can include things like authentication and authorisation checks, implementing rate limits and so on.. */ }, ['response']); Http::init(function($response) { /* Example of init method for group1. Do stuff that is common to all your endpoints in group1. This can include things like authentication and authorisation checks, implementing rate limits and so on.. */ }, ['response'], 'group1'); Http::init(function($response) { /* Example of init method for group2. Do stuff that is common to all your endpoints in group2. This can include things like authentication and authorisation checks, implementing rate limits and so on.. */ }, ['response'], 'group2'); Http::shutdown(function($request) { /* Example of global shutdown method. Do stuff that needs to be performed at the end of each request for all groups. '*' (Wildcard validator) is optional. This can include cleanups, logging information, recording usage stats, closing database connections and so on.. */ }, ['request'], '*'); Http::shutdown(function($request) { /* Example of shutdown method of group1. Do stuff that needs to be performed at the end of each request for all groups. This can include cleanups, logging information, recording usage stats, closing database connections and so on.. */ }, ['request'], 'group1'); $http->start(); ``` -------------------------------- ### Basic Utopia HTTP Application Setup Source: https://github.com/utopia-php/http/blob/master/README.md Demonstrates initializing the Utopia HTTP framework, setting up dependency injection for a custom user dependency, defining a GET route with response headers, and starting the HTTP server. ```PHP require_once __DIR__.'/../vendor/autoload.php'; use Utopia\DI\Container; use Utopia\DI\Dependency; use Utopia\Http\Http; use Utopia\Http\Request; use Utopia\Http\Response; use Utopia\Http\Adapter\FPM\Server; // Creating the dependency injection container $container = new Container(); // Adding a user dependency to the container $user = new Dependency(); $user ->setName('user') ->inject('request') // We can insert and use other injections as well ->setCallback(fn (Request $request) => $request->getHeader('x-user-id', 'John Doe')); $container->set($user); // Defining Route Http::get('/hello-world') ->inject('request') // Auto-injected each request ->inject('response') // Auto-injected each request ->inject('user') ->action( function(Request $request, Response $response, string $user) { $response ->addHeader('Cache-Control', 'no-cache, no-store, must-revalidate') ->addHeader('Expires', '0') ->addHeader('Pragma', 'no-cache') ->json(['message' => 'Hello World', 'user' => $user]); } ); Http::setMode(Http::MODE_TYPE_PRODUCTION); $http = new Http(new Server(), $container, 'America/New_York'); $http->start(); ``` -------------------------------- ### Define Basic GET Route with Swoole Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Demonstrates how to define a basic GET route using Utopia HTTP with a Swoole server. It shows how to inject request and response objects and define an action callback to send a response. ```php use Utopia\Http\Http; use Utopia\Http\Swoole\Request; use Utopia\Http\Swoole\Response; use Swoole\Http\Server; use Swoole\Http\Request as SwooleRequest; use Swoole\Http\Response as SwooleResponse; $http = new Server("0.0.0.0", 8080); Http::get('/') ->inject('request') ->inject('response') ->action( function($request, $response) { // Return raw HTML $response->send("
Hello World!
"); } ); $http->on('request', function (SwooleRequest $swooleRequest, SwooleResponse $swooleResponse) { $request = new Request($swooleRequest); $response = new Response($swooleResponse); $http = new Http('America/Toronto'); $http->run($request, $response); }); $http->start(); ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/utopia-php/http/blob/master/README.md Provides an example of setting up dependency injection using Utopia's Container and Dependency classes. It shows how to define a resource ('timing') and register it with the container. ```PHP use Utopia\DI\Container; use Utopia\DI\Dependency; $container = new Container(); $timing = new Dependency(); $timing ->setName('timing') ->setCallback(fn () => \microtime(true)); $container->add($timing); ``` -------------------------------- ### Utopia HTTP Route Definition Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Demonstrates defining an HTTP PUT endpoint for updating a todo item. It includes route parameters, descriptions, grouping, labeling, parameter validation, and dependency injection for the action. ```php Http::put('/todos/:id') ->desc('Update todo') ->groups(['group1', 'group2']) ->label('scope', 'public') ->label('abuse-limit', 50) ->param('id', "", new Wildcard(), 'id of the todo') ->param('task', "", new Wildcard(), 'name of the todo') ->param('is_complete', true, new Wildcard(), 'task complete or not') ->inject('response') ->action( function($id, $task, $is_complete, $response) { $path = \realpath('/http/http/todos.json'); $data = json_decode(file_get_contents($path)); foreach($data as $object){ if($object->id == $id){ $object->task = $task; $object->is_complete = $is_complete; break; } } $jsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); file_put_contents($path, $jsonData); $response->json($data); } ); ``` -------------------------------- ### Send Raw HTML Response Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Demonstrates how to send raw HTML content as a response using the `$response->send()` method. This is useful for rendering standard HTML pages. ```php $response->send("
Hello World!
"); ``` -------------------------------- ### Utopia HTTP PHP FPM Server Adapter Source: https://github.com/utopia-php/http/blob/master/README.md Example of configuring and starting the Utopia HTTP server using the PHP FPM adapter, defining a root route. ```PHP use Utopia\DI\Container; use Utopia\Http\Http; use Utopia\Http\Response; use Utopia\Http\Adapter\FPM\Server; Http::get('/') ->inject('response') ->action( function(Response $response) { $response->send('Hello from PHP FPM'); } ); $http = new Http(new Server(), new Container(), 'America/New_York'); $http->start(); ``` -------------------------------- ### Utopia HTTP Parameter Types Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Explains how Utopia HTTP handles different types of parameters: path, query, and body. It details the usage of the `param` method for defining these parameters and their availability in the action callback. ```APIDOC Utopia HTTP Parameter Handling: Utopia HTTP allows defining parameters for routes using the `->param()` method. These parameters can be path parameters, query parameters, or body parameters, and are made available to the `->action()` callback. 1. Path Parameters: - Specified using `:` in the route path (e.g., `/api/users/:userId`). - Defined in the route definition using `->param('param_name', , , '')`. - Example: ```php Http::get('/users/:userId') ->param('userId', '', new Utopia\Http\Validator\Numeric(), 'The ID of the user') ->action(function($userId) { /* ... */ }); ``` 2. Query Parameters: - Specified directly using the `->param()` function without a placeholder in the route path. - Example: ```php Http::get('/search') ->param('q', '', new Utopia\Http\Validator\Text(), 'The search query') ->action(function($q) { /* ... */ }); ``` 3. Body Parameters: - Also specified using the `->param()` function. - These are typically used in POST and PUT requests and are passed in the request body. - Example: ```php Http::post('/users') ->param('name', '', new Utopia\Http\Validator\Text(), 'The name of the user') ->param('email', '', new Utopia\Http\Validator\Email(), 'The email of the user') ->action(function($name, $email) { /* ... */ }); ``` Parameter Availability: - All defined parameters become available to the `->action()` callback function in the same order they were declared. ``` -------------------------------- ### Send HTTP Request Source: https://github.com/utopia-php/http/blob/master/README.md Example cURL command to send a GET request to the /hello-world endpoint. ```Bash curl http://localhost:8000/hello-world ``` -------------------------------- ### Utopia HTTP Swoole Server Adapter Source: https://github.com/utopia-php/http/blob/master/README.md Example of configuring and starting the Utopia HTTP server using the Swoole adapter, defining a root route with request and response injection. ```PHP use Utopia\DI\Container; use Utopia\Http\Http; use Utopia\Http\Request; use Utopia\Http\Response; use Utopia\Http\Adapter\Swoole\Server; Http::get('/') ->inject('request') ->inject('response') ->action( function(Request $request, Response $response) { $response->send('Hello from Swoole'); } ); $http = new Http(new Server('0.0.0.0', '80' , ['open_http2_protocol' => true]), new Container(), 'America/New_York'); $http->start(); ``` -------------------------------- ### Send HTTP Requests with Parameters Source: https://github.com/utopia-php/http/blob/master/README.md Example cURL commands to send GET requests to an endpoint, demonstrating default parameter usage and passing custom parameters. ```Bash curl http://localhost:8000/hello-world curl http://localhost:8000/hello-world?name=Utopia curl http://localhost:8000/hello-world?name=Appwrite ``` -------------------------------- ### Send JSON Response Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Illustrates sending JSON data as a response by passing a PHP array or object to the `$response->json()` method. This is ideal for APIs. ```php $response->json(['Goodbye' => 'World']); ``` -------------------------------- ### Set Response Status Code Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Shows how to set a specific HTTP status code for the response using the `$response->setStatusCode()` method, followed by sending the response body. ```php $response ->setStatusCode(200) ->send('') ``` -------------------------------- ### Define PUT Route with Parameters and File Update Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md Illustrates defining a PUT route to update a todo item in a JSON file. It showcases parameter injection for route variables and request body data, and how to handle file operations and JSON responses. ```php Http::put('/todos/:id') ->param('id', "", new Utopia\Http\Validator\Wildcard(), 'id of the todo') ->param('task', "", new Utopia\Http\Validator\Wildcard(), 'name of the todo') ->param('is_complete', true, new Utopia\Http\Validator\Wildcard(), 'task complete or not') ->inject('response') ->action( function($id, $task, $is_complete, $response) { $path = \realpath('/http/http/todos.json'); $data = json_decode(file_get_contents($path)); foreach($data as $object){ if($object->id == $id){ $object->task = $task; $object->is_complete = $is_complete; break; } } $jsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); file_put_contents($path, $jsonData); $response->json($data); } ); ``` -------------------------------- ### Define Endpoint with Parameters Source: https://github.com/utopia-php/http/blob/master/README.md Example of defining an HTTP GET endpoint that accepts a 'name' parameter with a default value and a validator, and injects the response object. ```PHP Http::get('/') ->param('name', 'World', new Text(256), 'Name to greet. Optional, max length 256.', true) ->inject('response') ->action(function(string $name, Response $response) { $response->send('Hello ' . $name); }); ``` -------------------------------- ### Utopia PHP HTTP Init Method Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md The init method is executed at the beginning of a request lifecycle. It's used for common tasks like authentication, authorization, and rate limiting across all specified endpoint groups. ```php Http::init(function($response) { /* Do stuff that is common to all your endpoints. This can include things like authentication and authorisation checks, implementing rate limits and so on.. */ }, ['response'], '*'); ``` -------------------------------- ### Install Utopia HTTP via Composer Source: https://github.com/utopia-php/http/blob/master/README.md Installs the Utopia HTTP library using Composer, the dependency manager for PHP. ```Bash composer require utopia-php/http ``` -------------------------------- ### Run HTTP Server Source: https://github.com/utopia-php/http/blob/master/README.md Command to start the PHP built-in web server for the Utopia HTTP application. ```Bash php -S localhost:8000 src/server.php ``` -------------------------------- ### Utopia PHP HTTP Shutdown Method Source: https://github.com/utopia-php/http/blob/master/docs/Getting-Starting-Guide.md The shutdown method is executed at the end of a request lifecycle for performing cleanup tasks. This includes closing database connections, resetting flags, or triggering analytics events. ```php Http::shutdown(function($request) { /* Do stuff that needs to be performed at the end of each request. This can include cleanups, logging information, recording usage stats, closing database connections and so on.. */ }, ['request'], '*'); ``` -------------------------------- ### Branch Naming Convention Example Source: https://github.com/utopia-php/http/blob/master/CONTRIBUTING.md An example of a branch name following the convention TYPE-ISSUE_ID-DESCRIPTION, used for organizing contributions. ```Git doc-548-submit-a-pull-request-section-to-contribution-guide ``` -------------------------------- ### Docker Compose Testing Commands Source: https://github.com/utopia-php/http/blob/master/CONTRIBUTING.md Commands to set up and run tests for the Utopia HTTP project using Docker Compose, targeting different PHP SAPI environments. ```Docker docker compose up -d ``` ```Docker docker compose exec fpm vendor/bin/phpunit --configuration phpunit.xml ``` ```Docker docker compose exec swoole vendor/bin/phpunit --configuration phpunit.xml ``` ```Docker docker compose exec swoole-coroutine vendor/bin/phpunit --configuration phpunit.xml ``` -------------------------------- ### Init, Shutdown, and Error Hooks Source: https://github.com/utopia-php/http/blob/master/README.md Demonstrates how to define and register init, shutdown, and error hooks within the Utopia PHP HTTP lifecycle. These hooks allow custom logic execution before route actions, after route actions, or during error handling. ```PHP Http::init() ->inject('request') ->action(function(Request $request) { \var_dump("Recieved: " . $request->getMethod() . ' ' . $request->getURI()); }); Http::shutdown() ->inject('response') ->action(function(Response $response) { \var_dump('Responding with status code: ' . $response->getStatusCode()); }); Http::error() ->inject('error') ->inject('response') ->action(function(\Throwable $error, Response $response) { $response ->setStatusCode(500) ->send('Error occurred ' . $error); }); ``` -------------------------------- ### Git Workflow Commands Source: https://github.com/utopia-php/http/blob/master/CONTRIBUTING.md Essential Git commands for contributing, including pulling upstream changes, creating new branches, and pushing changes to GitHub. ```Git git pull ``` ```Git git checkout -b [name_of_your_new_branch] ``` ```Git git push origin [name_of_your_new_branch] ``` -------------------------------- ### Injecting Resources into Endpoint Actions Source: https://github.com/utopia-php/http/blob/master/README.md Demonstrates how to inject a previously defined resource ('timing') into an HTTP endpoint's action function. The injected resource is available as a typed parameter within the action. ```PHP Http::get('/') ->inject('timing') ->inject('response') ->action(function(float $timing, Response $response) { $response->send('Request Unix timestamp: ' . \strval($timing)); }); ``` -------------------------------- ### Injecting Resources into Hooks Source: https://github.com/utopia-php/http/blob/master/README.md Illustrates injecting a resource ('timing') into a shutdown hook. This allows the hook to access context or data prepared by the resource during the request lifecycle. ```PHP Http::shutdown() ->inject('timing') ->action(function(float $timing) { $difference = \microtime(true) - $timing; \var_dump("Request took: " . $difference . " seconds"); }); ``` -------------------------------- ### Group-Specific Hooks Source: https://github.com/utopia-php/http/blob/master/README.md Shows how to define an init hook that is restricted to execute only for endpoints belonging to the 'api' group. This demonstrates conditional hook execution based on endpoint grouping. ```PHP Http::init() ->groups(['api']) ->inject('request') ->inject('response') ->action(function(Request $request, Response $response) { $apiKey = $request->getHeader('x-api-key', ''); if(empty($apiKey)) { $response ->setStatusCode(Response::STATUS_CODE_UNAUTHORIZED) ->send('API key missing.'); } }); ``` -------------------------------- ### Endpoint Grouping Source: https://github.com/utopia-php/http/blob/master/README.md Illustrates how to assign groups to specific HTTP endpoints. This feature allows for conditional execution of hooks based on defined group names, enabling better organization and modularity. ```PHP Http::get('/v1/health') ->groups(['api', 'public']) ->inject('response') ->action( function(Response $response) { $response->send('OK'); } ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.