utopia-php / framework
A simple, light and advanced PHP HTTP framework
Installs: 262 758
Dependents: 10
Suggesters: 0
Security: 0
Stars: 270
Watchers: 16
Forks: 32
Open Issues: 13
Requires
- php: >=8.0
- ext-swoole: *
- utopia-php/servers: 0.1.*
Requires (Dev)
- ext-xdebug: *
- laravel/pint: ^1.2
- phpbench/phpbench: ^1.2
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.5.25
- swoole/ide-helper: 4.8.3
- dev-master
- 1.0.2
- 1.0.1
- 1.0.0
- 1.0.0-RC3
- 1.0.0-RC2
- 1.0.0-RC1
- 0.x-dev
- 0.34.3
- 0.34.2
- 0.34.1
- 0.34.0
- 0.33.x-dev
- 0.33.15
- 0.33.14
- 0.33.13
- 0.33.12
- 0.33.11
- 0.33.10
- 0.33.9
- 0.33.8
- 0.33.7
- 0.33.6
- 0.33.4
- 0.33.3
- 0.33.2
- 0.33.1
- 0.33.0
- 0.32.x-dev
- 0.32.0
- 0.31.x-dev
- 0.31.1
- 0.31.0
- 0.30.0
- 0.29.0
- 0.28.4
- 0.28.3
- 0.28.2
- 0.28.1
- 0.28.0
- 0.27.0
- 0.26.3
- 0.26.2
- 0.26.1
- 0.26.0
- 0.25.1
- 0.25.0
- 0.24.0
- 0.23.4
- 0.23.2
- 0.23.1
- 0.23.0
- 0.22.1
- 0.22.0
- 0.21.1
- 0.21.0
- 0.20.0
- 0.19.21
- 0.19.20
- 0.19.9
- 0.19.8
- 0.19.7
- 0.19.6
- 0.19.5
- 0.19.4
- 0.19.3
- 0.19.2
- 0.19.1
- 0.19.0
- 0.18.x-dev
- 0.18.1
- 0.18.0
- 0.17.3
- 0.17.2
- 0.17.1
- 0.17.0
- 0.16.2
- 0.16.1
- 0.16.0
- 0.15.1
- 0.15.0
- 0.14.1
- 0.14.0
- 0.13.0
- 0.12.3
- 0.12.2
- 0.12.1
- 0.12.0
- 0.11.0
- 0.10.2
- 0.10.1
- 0.10.0
- 0.9.8
- 0.9.7
- 0.9.6
- 0.9.5
- 0.9.4
- 0.9.3
- 0.9.2
- 0.9.1
- 0.9.0
- 0.8.4
- 0.8.3
- 0.8.2
- 0.8.1
- 0.8.0
- 0.7.6
- 0.7.5
- 0.7.4
- 0.7.3
- 0.7.2
- 0.7.1
- 0.7.0
- 0.6.0
- 0.5.1
- 0.5.0
- 0.4.1
- 0.4.0
- 0.3.7
- 0.3.6
- 0.3.5
- 0.3.4
- 0.3.3
- 0.3.2
- 0.3.1
- 0.3.0
- 0.2.0
- v0.1.1
- v0.1.0
- dev-fix-catch-error-handler
- dev-fix-prevent-duplicate-compression
- dev-memory-profile
- dev-fix-site-compressiong
- dev-telemetry
- dev-fix-optional-null
- dev-feat-utopia-compression
- dev-chore-update-compression
- dev-opentelemetry
- dev-feat-framework-v2
- dev-feat-0.33-implement-numeric-whitelist
- dev-feat-base-servers
- dev-feat-test-multiple-php-versions
- dev-feat-host-wildcard-validator
- dev-make-default-param-callable
- dev-default-param-supports-function
- dev-feat-v2
- dev-feat-add-multiple-validator-to-v2
- dev-feat-add-multiple-validator
- dev-feat-domain-validator-check-scheme
- dev-feat-improve-error-message
- dev-fix-coroutine-style-two
- dev-fix-router-behaviour
- dev-fix-coroutines-style2
- dev-fix-coroutine-style
- dev-feat-cloud
- dev-fix-trailing-slashes-master
- dev-fix-trailing-slash
- dev-backport-fix-route-mismatch
- dev-fix-wildcards-g4
- dev-fix-wildcard-edge-cases
- dev-feat-traits
- dev-chore-cleanup
- dev-feat-allow-error-overrides
- dev-fix-bool-validator
- dev-improve-hostname-validator
- dev-fix-race-condition
- dev-feat-get-request-headers
- dev-error-handler-message
- dev-feat-setter-returns
- dev-feat-allow-mutations
- dev-fix-move-labels-to-hook
- dev-feat-disable-route-if-response-sent
- dev-feat-add-default-exception-handler
- dev-feat-allow-fresh-match
- dev-fix-options-hook
- dev-feat-hooks
- dev-feat-unkeyed-full-body-params
- dev-feat-public-add-route
- dev-feat-graphql-helpers
- dev-feat-backport-appwrite-validators
- dev-improve-hostname-validaotr
- dev-fix-cookies-expiry
- dev-feat-head-request
- dev-feat-php-8-1
- dev-feat-add-server-support
- dev-feat-add-new-status-code
- dev-feat-args-resource
- dev-fix-cookie-name-case
- dev-feat-improve-typing
- dev-add-utopia-database-to-readme
- dev-feat-range-validator-infinity
- dev-feat-numeric-validators
- dev-fix-getResource-utopia-resource
- dev-fix-sensitivity-error
- dev-feat-add-wildcard
- dev-fix-phpdocs-description
- dev-fix-head-method-routing
- dev-fix-router-fix
- dev-feat-upgrade-injection
- dev-fix-for-0.4
- dev-statis-routes
This package is auto-updated.
Last update: 2024-12-11 14:18:14 UTC
README
Utopia HTTP is a PHP MVC based framework with minimal must-have features for professional, simple, advanced and secure web development. This library is maintained by the Appwrite team.
Utopia HTTP is almost dependency-free. Any extra features, such as authentication or caching are available as standalone models in order to keep the framework core clean, light, and easy to learn.
Getting Started
Install using Composer:
composer require utopia-php/http
Init your first application in src/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->add($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();
Run HTTP server:
php -S localhost:8000 src/server.php
Send HTTP request:
curl http://localhost:8000/hello-world
Server Adapters
The library supports server adapters to be able to run on any PHP setup. You could use the FPM or Swoole server.
Use PHP FPM server
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();
When using PHP FPM, you can use the command
php -S localhost:80 src/server.php
to run the HTTP server locally
Using Swoole server
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();
When using Swoole, you can use the command
php src/server.php
to run the HTTP server locally, but you need Swoole installed. For setup with Docker, check out our example application
Parameters
Parameters are used to receive input into endpoint action from the HTTP request. Parameters could be defined as URL parameters or in a body with a structure such as JSON.
Every parameter must have a validator defined. Validators are simple classes that verify the input and ensure the security of inputs. You can define your own validators or use some of built-in validators.
Define an endpoint with params:
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); });
Send HTTP requests to ensure the parameter works:
curl http://localhost:8000/hello-world curl http://localhost:8000/hello-world?name=Utopia curl http://localhost:8000/hello-world?name=Appwrite
It's always recommended to use params instead of getting params or body directly from the request resource. If you do that intentionally, always make sure to run validation right after fetching such a raw input.
Hooks
There are three types of hooks:
- Init hooks are executed before the route action is executed
- Shutdown hooks are executed after route action is finished, but before application shuts down
- Error hooks are executed whenever there's an error in the application lifecycle.
You can provide multiple hooks for each stage. If you do not assign groups to the hook, by default, the hook will be executed for every route. If a group is defined on a hook, it will only run during the lifecycle of a request with the same group name on the action.
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); });
Hooks are designed to be actions that run during the lifecycle of requests. Hooks should include functional logic. Hooks are not designed to prepare dependencies or context for the request. For such a use case, you should use resources.
Groups
Groups allow you to define common behavior for multiple endpoints.
You can start by defining a group on an endpoint. Keep in mind you can also define multiple groups on a single endpoint.
Http::get('/v1/health') ->groups(['api', 'public']) ->inject('response') ->action( function(Response $response) { $response->send('OK'); } );
Now you can define hooks that would apply only to specific groups. Remember, hooks can also be assigned to multiple groups.
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.'); } });
Groups are designed to be actions that run during the lifecycle of requests to endpoints that have some logic in common. Groups allow you to prevent code duplication and are designed to be defined anywhere in your source code to allow flexibility.
Injections
Injections allow you to prepare dependencies for requests such as database connection or the user who sent the request. A new instance of a resource is created for every request.
We define an injection using a Container:
use Utopia\DI\Container; use Utopia\DI\Dependency; $container = new Container(); $timing = new Dependency(); $timing ->setName('timing') ->setCallback(fn () => \microtime(true)); $container->add($timing);
Inject resource into endpoint action:
Http::get('/') ->inject('timing') ->inject('response') ->action(function(float $timing, Response $response) { $response->send('Request Unix timestamp: ' . \strval($timing)); });
Inject resource into a hook:
Http::shutdown() ->inject('timing') ->action(function(float $timing) { $difference = \microtime(true) - $timing; \var_dump("Request took: " . $difference . " seconds"); });
In advanced scenarios, resources can also be injected into other resources or endpoint parameters.
Resources are designed to prepare dependencies or context for the request. Resources are not meant to do functional logic or return callbacks. For such a use case, you should use hooks.
To learn more about architecture and features for this library, check out more in-depth Getting started guide.
System Requirements
Utopia HTTP requires PHP 8.1 or later. We recommend using the latest PHP version whenever possible.
More from Utopia
Our ecosystem supports other thin PHP projects aiming to extend the core PHP Utopia HTTP.
Each project is focused on solving a single, very simple problem and you can use composer to include any of them in your next project.
You can find all libraries in GitHub Utopia organization.
Contributing
All code contributions - including those of people having commit access - must go through a pull request and approved by a core developer before being merged. This is to ensure proper review of all the code.
Fork the project, create a feature branch, and send us a pull request.
You can refer to the Contributing Guide for more info.
For security issues, please email security@appwrite.io instead of posting a public issue in GitHub.
Copyright and license
The MIT License (MIT) http://www.opensource.org/licenses/mit-license.php