PHP code example of utopia-php / framework

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

    

utopia-php / framework example snippets




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();

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();

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();

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);
    });

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);
    });

Http::get('/v1/health')
    ->groups(['api', 'public'])
    ->inject('response')
    ->action(
        function(Response $response) {
            $response->send('OK');
        }
    );

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.');
        }
    });

use Utopia\DI\Container;
use Utopia\DI\Dependency;

$container = new Container();

$timing = new Dependency();
$timing
    ->setName('timing')
    ->setCallback(fn () => \microtime(true));

$container->add($timing);

Http::get('/')
    ->inject('timing')
    ->inject('response')
    ->action(function(float $timing, Response $response) {
        $response->send('Request Unix timestamp: ' . \strval($timing));
    });

Http::shutdown()
    ->inject('timing')
    ->action(function(float $timing) {
        $difference = \microtime(true) - $timing;
        \var_dump("Request took: " . $difference . " seconds");
    });
bash
php -S localhost:8000 src/server.php