PHP code example of usox / sharesta

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

    

usox / sharesta example snippets



final class HomeRoute implements \JsonSerializable {

    public function jsonSerialize(): string {
        return 'Welcome home';
    }
}

final class UpdateUserRoute implements \JsonSerializable {

    public function __construct(
        private int $user_id,
        private \Usox\Sharesta\RequestInterface $request
    ): void {
    }

    public function jsonSerialize(): bool {
        // do some magic, e.g. access the request body by $this->request
        return true;
    }

}

final class Routes implements Usox\Sharesta\RoutesInterface {

    public function registerRoutes(Usox\Sharesta\RouterInterface $router): void {
        $router->get(
            '/',
            (Usox\Sharesta\RequestInterface $request): \JsonSerializable ==> {
                return new HomeRoute();
            }
        );

        /**
         * Get variables from the path (e.g. `http://some.tld/users/123`)
         */
        $router->post(
            '/users/:id',
            (Usox\Sharesta\RequestInterface $request): \JsonSerializable ==> {
                return new UpdateUserRoute(
                    $request->getUriValues('id'),
                    $request->getRequestBody()
                );
            }
        );
    }
}

<?hh // strict

>>
function main(): noreturn {
	/* HH_IGNORE_ERROR[2050] */ $get_vars = dict($_GET);
	/* HH_IGNORE_ERROR[2050] */ $server_vars = dict($_SERVER);

    $factory = new Usox\Sharesta\ApiFactory();
    $router = $factory->createRouter(
        $server_vars,
        $get_vars
    );

    $routes = new Routes();
    $routes->registerRoutes($router);

    $router->route(
        '' // path to the file. Leave it empty if your server configuration defaults to index.hh
    );

    die(0);
}