PHP code example of tobento / app-http

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

    

tobento / app-http example snippets


use Tobento\App\AppFactory;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Http::class);

// Run the app
$app->run();

use Tobento\App\AppFactory;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use Tobento\Service\Uri\AssetUriInterface;
use Tobento\Service\Uri\BaseUriInterface;
use Tobento\Service\Uri\CurrentUriInterface;
use Tobento\Service\Uri\PreviousUriInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Http::class);
$app->booting();

// PSR-7
$request = $app->get(ServerRequestInterface::class);
$response = $app->get(ResponseInterface::class);

// returns UriInterface
$assetUri = $app->get(AssetUriInterface::class);
$baseUri = $app->get(BaseUriInterface::class);
$currentUri = $app->get(CurrentUriInterface::class);
$previousUri = $app->get(PreviousUriInterface::class);
// Session Boot is needed, otherwise it is always same as base uri.

// PSR-17
$responseFactory = $app->get(ResponseFactoryInterface::class);
$streamFactory = $app->get(StreamFactoryInterface::class);
$uploadedFileFactory = $app->get(UploadedFileFactoryInterface::class);
$uriFactory = $app->get(UriFactoryInterface::class);

// Run the app
$app->run();

use function Tobento\App\Http\{assetUri, baseUri};
use Tobento\Service\Uri\AssetUriInterface;
use Tobento\Service\Uri\BaseUriInterface;

var_dump(assetUri() instanceof AssetUriInterface);
// bool(true)

var_dump(baseUri() instanceof BaseUriInterface);
// bool(true)

use Tobento\App\AppFactory;
use Tobento\Service\Requester\RequesterInterface;
use Tobento\Service\Responser\ResponserInterface;

// Create the app
$app = (new AppFactory())->createApp();

// You may add the session boot to enable
// flash messages and flash input data.
$app->boot(\Tobento\App\Http\Boot\Session::class);

$app->boot(\Tobento\App\Http\Boot\RequesterResponser::class);
$app->booting();

$requester = $app->get(RequesterInterface::class);
$responser = $app->get(ResponserInterface);

// Run the app
$app->run();

use Tobento\App\AppFactory;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Middleware::class);
$app->booting();

// add middleware aliases using app macro:
$app->middlewareAliases([
    'alias' => FooMiddleware::class,
]);

// add middleware group using app macro:
$app->middlewareGroup(name: 'api', middlewares: [
    Middleware::class,
]);

// add middleware using app macro:
$app->middleware(BarMiddleware::class);

// Run the app
$app->run();

return [
    // ...
    'middlewares' => [
        // priority => middleware
        
        // via fully qualified class name:
        8000 => \Tobento\App\Http\Middleware\SecurePolicyHeaders::class,
        
        // with build-in parameters:
        7900 => [AnotherMiddleware::class, 'name' => 'Sam'],
        
        // by alias:
        7800 => 'aliasedMiddleware',
        
        // by group name:
        7800 => 'groupedMiddlewares',
        
        // by class instance:
        7700 => new SomeMiddleware(),
    ],
];

use Tobento\App\Boot;
use Tobento\App\Http\Boot\Middleware;

class MyMiddlewareBoot extends Boot
{
    public const BOOT = [
        // you may ensure the middleware boot.
        Middleware::class,
    ];
    
    public function boot(Middleware $middleware)
    {
        $middleware->add(MyMiddleware::class);
    }
}

use Tobento\App\Boot;
use Tobento\App\Http\Boot\Middleware;

class MyMiddlewareBoot extends Boot
{
    public const BOOT = [
        // you may ensure the middleware boot.
        Middleware::class,
    ];
    
    public function boot(Middleware $middleware)
    {
        $middleware->addAliases([
            'alias' => MyMiddleware::class,
        ]);
        
        // add by alias:
        $middleware->add('alias');
    }
}

return [
    // ...
    'aliases' => [
        'alias' => MyMiddleware::class,
    ],
];

use Tobento\App\Boot;
use Tobento\App\Http\Boot\Middleware;

class MyMiddlewareBoot extends Boot
{
    public const BOOT = [
        // you may ensure the middleware boot.
        Middleware::class,
    ];
    
    public function boot(Middleware $middleware)
    {
        $middleware->addGroup(name: 'api', middlewares: [
            Middleware::class,
            // with build-in parameters:
            [AnotherMiddleware::class, 'name' => 'Sam'],
            // by alias:
            'aliasedMiddleware',
            // by class instance:
            new SomeMiddleware(),
        ]);
        
        // add by group:
        $middleware->add('api');
    }
}

return [
    // ...
    'groups' => [
        'name' => [
            SomeMiddleware::class,
        ],
    ],
];

$previousUri = $app->get(PreviousUriInterface::class);

$response = $response->withHeader('X-Exclude-Previous-Url', '1');

'middlewares' => [
    8000 => \Tobento\App\Http\Middleware\SecurePolicyHeaders::class,
],

<style nonce="<?= $view->esc($view->get('cspNonce', '')) 

use Tobento\App\AppFactory;
use Tobento\Service\Routing\RouterInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Routing::class);
$app->booting();

// using interface:
$router = $app->get(RouterInterface::class);
$router->get('blog', function() {
    return ['page' => 'blog'];
});

// using macros:
$app->route('GET', 'foo', function() {
    return ['page' => 'foo'];
});

// Run the app
$app->run();

use Tobento\App\Boot;
use Tobento\Service\Routing\RouterInterface;
use Tobento\Service\Routing\RouteGroupInterface;

class RoutesBoot extends Boot
{
    public const BOOT = [
        // you may ensure the routing boot.
        \Tobento\App\Http\Boot\Routing::class,
    ];
    
    public function boot(RouterInterface $router)
    {
        // Add routes on the router
        $router->get('blog', [Controller::class, 'method']);
        
        // Add routes with the provided app macros
        $this->app->route('GET', 'blog', [Controller::class, 'method']);
        
        $this->app->routeGroup('admin', function(RouteGroupInterface $group) {

            $group->get('blog/{id}', function($id) {
                // do something
            });
        });
        
        $this->app->routeResource('products', ProductsController::class);
        
        $this->app->routeMatched('blog.edit', function() {
            // do something after the route has been matched.
        });
        
        $url = $this->app->routeUrl('blog.edit', ['id' => 5])->get();
    }
}

use Tobento\App\AppFactory;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(RoutesBoot::class);

// Run the app
$app->run();

use Tobento\App\AppInterface;
use Tobento\Service\Routing\RouteInterface;
use Tobento\Service\Routing\RouteHandlerInterface;
use Tobento\App\Http\Routing\DeclaredHandlerParameters;
use Tobento\App\Http\Routing\ArgumentsHandlerParameters;
use Psr\Http\Message\ServerRequestInterface;

final class CustomRouteHandler implements RouteHandlerInterface
{
    public function __construct(
        private AppInterface $app
    ) {}
    
    /**
     * Handles the route.
     *
     * @param RouteInterface $route
     * @param null|ServerRequestInterface $request
     * @return mixed The return value of the handler called.
     */
    public function handle(RouteInterface $route, null|ServerRequestInterface $request = null): mixed
    {
        // You may interfere with the arguments for the route handler to be called:
        $arguments = $route->getParameter('_arguments');
        
        var_dump($arguments instanceof ArgumentsHandlerParameters);
        // bool(true)
        
        // You may use the declared route handler parameters:
        $declared = $route->getParameter('_declared');
        
        var_dump($declared instanceof DeclaredHandlerParameters);
        // bool(true)
        
        // Let further handlers handle it:
        return [$route, $request];
        
        // Or prevent further handlers from being called
        // and returning the route handler result:
        $result = $this->app->call($route->getHandler(), $arguments->getParameters());
        
        return [$route, $request, $result];
    }
}

use Tobento\App\Http\Routing\RouteHandlerInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots:
$app->boot(\Tobento\App\Http\Boot\Routing::class);

// Add route handler using the app on method:
$app->on(RouteHandlerInterface::class, function(RouteHandlerInterface $handler) {
    $handler->addHandler(CustomRouteHandler::class);
})->priority(1500);

// Run the app
$app->run();

use Tobento\App\AppFactory;
use Tobento\Service\Session\SessionInterface;
use Psr\Http\Message\ServerRequestInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Middleware::class);
$app->boot(\Tobento\App\Http\Boot\Routing::class);
$app->boot(\Tobento\App\Http\Boot\Session::class);
$app->booting();

$app->route('GET', 'foo', function(SessionInterface $session) {
    $session->set('key', 'value');
    return ['page' => 'foo'];
});

// or you may get the session from the request attributes:
$app->route('GET', 'bar', function(ServerRequestInterface $request) {
    $session = $request->getAttribute(SessionInterface::class);
    $session->set('key', 'value');
    return ['page' => 'bar'];
});

// Run the app
$app->run();

use Tobento\App\Boot;
use Tobento\App\Http\HttpErrorHandlersInterface;
use Tobento\Service\Session\SessionStartException;
use Tobento\Service\Session\SessionExpiredException;
use Tobento\Service\Session\SessionValidationException;
use Tobento\Service\Session\SessionSaveException;
use Throwable;

class HttpErrorHandlerBoot extends Boot
{
    public const BOOT = [
        // you may ensure the http boot.
        \Tobento\App\Http\Boot\Http::class,
    ];
    
    public function boot()
    {
        $this->app->on(HttpErrorHandlersInterface::class, function(HttpErrorHandlersInterface $handlers) {

            $handlers->add(function(Throwable $t) {
                
                if ($t instanceof SessionStartException) {
                    // You may do something if starting session fails.
                } elseif ($t instanceof SessionExpiredException) {
                    // This is already handled by the session middleware,
                    // so you might check it out.
                } elseif ($t instanceof SessionValidationException) {
                    // You may do something if session validation fails. 
                } elseif ($t instanceof SessionSaveException) {
                    // You may do something if saving session fails. 
                }
                
                return $t;
            })->priority(2000); // you might add a priority.
        });
    }
}

use Tobento\App\AppFactory;
use Tobento\Service\Cookie\CookiesFactoryInterface;
use Tobento\Service\Cookie\CookieFactoryInterface;
use Tobento\Service\Cookie\CookieValuesFactoryInterface;
use Tobento\Service\Cookie\CookiesProcessorInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Cookies::class);
$app->booting();

// The following interfaces are available after booting:
$cookiesFactory = $app->get(CookiesFactoryInterface::class);
$cookieFactory = $app->get(CookieFactoryInterface::class);
$cookieValuesFactory = $app->get(CookieValuesFactoryInterface::class);
$cookiesProcessor = $app->get(CookiesProcessorInterface::class);

// Run the app
$app->run();

use Tobento\App\AppFactory;
use Tobento\Service\Cookie\CookieValuesInterface;
use Tobento\Service\Cookie\CookiesInterface;
use Psr\Http\Message\ServerRequestInterface;

// Create the app
$app = (new AppFactory())->createApp();

// Adding boots
$app->boot(\Tobento\App\Http\Boot\Routing::class);
$app->boot(\Tobento\App\Http\Boot\Cookies::class);
$app->booting();

$app->route('GET', 'bar', function(ServerRequestInterface $request) {

    // read cookies:
    $cookieValues = $request->getAttribute(CookieValuesInterface::class);
    
    $value = $cookieValues->get('foo');
    
    // or
    var_dump($request->getCookieParams());
    
    // write cookies:
    $cookies = $request->getAttribute(CookiesInterface::class);
    
    $cookies->add('name', 'value');
    
    return ['page' => 'bar'];
});

// Run the app
$app->run();

// ...

$app->boot(\Tobento\App\Encryption\Boot\Encryption::class);
$app->boot(\Tobento\App\Http\Boot\Cookies::class);

// ...

use Tobento\Service\Cookie\CookiesProcessorInterface;

$cookiesProcessor = $app->get(CookiesProcessorInterface::class);

$cookiesProcessor->whitelistCookie(name: 'name');

// or
$cookiesProcessor->whitelistCookie(name: 'name[foo]');
$cookiesProcessor->whitelistCookie(name: 'name[bar]');

use Tobento\Service\Cookie;
use Tobento\Service\Encryption;
use Psr\Container\ContainerInterface;

return [

    'middlewares' => [
        Cookie\Middleware\Cookies::class,
    ],

    'interfaces' => [

        //...

        Cookie\CookiesProcessorInterface::class => Cookie\CookiesProcessor::class,

        // or you may use a specified encrypter only for cookies:
        Cookie\CookiesProcessorInterface::class => static function(ContainerInterface $c): Cookie\CookiesProcessorInterface {

            $encrypter = null;

            if (
                $c->has(Encryption\EncryptersInterface::class)
                && $c->get(Encryption\EncryptersInterface::class)->has('cookies')
            ) {
                $encrypter = $c->get(Encryption\EncryptersInterface::class)->get('cookies');
            }

            return new Cookie\CookiesProcessor(
                encrypter: $encrypter,
                whitelistedCookies: [],
            );
        },
    ],

    //...
];

// ...
$app->boot(\Tobento\App\Http\Boot\ErrorHandler::class);
// ...

use Tobento\App\Http\Exception\HttpException;
use Tobento\App\Http\Exception\NotFoundException;

class SomeController
{
    public function index()
    {
        throw new HttpException(statusCode: 404);
        
        // or:
        throw new NotFoundException();
    }
}

use Tobento\Service\View;
use Tobento\Service\Dir\Dirs;
use Tobento\Service\Dir\Dir;

// ...
$app->set(View\ViewInterface::class, function() {
    return new View\View(
        new View\PhpRenderer(
            new Dirs(
                new Dir('home/private/views/'),
            )
        ),
        new View\Data(),
        new View\Assets('home/public/src/', 'https://www.example.com/src/')
    );
});
// ...

use Tobento\App\Http\Boot\ErrorHandler;
use Tobento\Service\Requester\RequesterInterface;
use Tobento\Service\Responser\ResponserInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class CustomErrorHandler extends ErrorHandler
{
    public function handleThrowable(Throwable $t): Throwable|ResponseInterface
    {
        $requester = $this->app->get(RequesterInterface::class);
        
        if ($t instanceof SomeException) {
            return $requester->wantsJson()
                ? $this->renderJson(code: 404)
                : $this->renderView(code: 404);
            
            // or with custom message:
            return $requester->wantsJson()
                ? $this->renderJson(code: 404, message: 'Custom')
                : $this->renderView(code: 404, message: 'Custom');
                
            // or with custom message and message parameters:
            return $requester->wantsJson()
                ? $this->renderJson(code: 404, message: 'Custom :value', parameters: [':value' => 'foo'])
                : $this->renderView(code: 404, message: 'Custom :value', parameters: [':value' => 'foo']);   
        }
        
        // using the responser:
        if ($t instanceof SomeOtherException) {
            $responser = $this->app->get(ResponserInterface::class);
            
            return $responser->json(
                data: ['key' => 'value'],
                code: 200,
            );
        }        
        
        return parent::handleThrowable($t);
    }
}

// ...
$app->boot(CustomErrorHandler::class);
// ...

use Tobento\App\Http\Boot\ErrorHandler;
use Tobento\Service\Requester\RequesterInterface;
use Tobento\Service\Responser\ResponserInterface;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class PrioritizedErrorHandler extends ErrorHandler
{
    protected const HANDLER_PRIORITY = 5000;
    
    public function handleThrowable(Throwable $t): Throwable|ResponseInterface
    {
        $requester = $this->app->get(RequesterInterface::class);
        
        if ($t instanceof SomeException) {
            return $requester->wantsJson()
                ? $this->renderJson(code: 404)
                : $this->renderView(code: 404);
        }
        
        // using the responser:
        if ($t instanceof SomeOtherException) {
            $responser = $this->app->get(ResponserInterface::class);
            
            return $responser->json(
                data: ['key' => 'value'],
                code: 200,
            );
        }        
        
        // return throwable to let other handler handle it:
        return $t;
    }
}

// ...
$app->boot(PrioritizedErrorHandler::class);

$app->boot(DefaultErrorHandler::class);

// you could boot it after the default,
// it gets called first if priority is higher as default:
$app->boot(PrioritizedErrorHandler::class);
// ...
app/config/http.php
app/config/middleware.php
app/config/middleware.php
app/config/middleware.php
app/config/middleware.php
Content-Security-Policy
app/config/http.php

php ap route:list
app/config/session.php
app/config/cookies.php
app/config/cookies.php
exception/403.php
exception/403.xml.php
exception/error.php
exception/error.xml.php