PHPackages                             tobento/app-http - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. tobento/app-http

ActiveLibrary[HTTP &amp; Networking](/categories/http)

tobento/app-http
================

App http support.

2.0.3(3mo ago)026220MITPHPPHP &gt;=8.4

Since Oct 8Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/tobento-ch/app-http)[ Packagist](https://packagist.org/packages/tobento/app-http)[ Docs](https://www.tobento.ch)[ RSS](/packages/tobento-app-http/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (10)Dependencies (33)Versions (27)Used By (20)

App Http
========

[](#app-http)

Http, routing, middleware and session support for the app.

Table of Contents
-----------------

[](#table-of-contents)

- [Getting Started](#getting-started)
    - [Requirements](#requirements)
- [Documentation](#documentation)
    - [App](#app)
    - [Http Boot](#http-boot)
        - [Http Config](#http-config)
        - [Request And Response](#request-and-response)
        - [Http Functions](#http-functions)
        - [Swap PSR-7 And PSR-17 Implementation](#swap-psr-7-and-psr-17-implementation)
    - [Requester And Responser Boot](#requester-and-responser-boot)
    - [Middleware Boot](#middleware-boot)
        - [Add Middleware via Config](#add-middleware-via-config)
        - [Add Middleware via Boot](#add-middleware-via-boot)
        - [Middleware Aliases](#middleware-aliases)
        - [Middleware Groups](#middleware-groups)
        - [Available Middleware](#available-middleware)
            - [Previous Uri Session Middleware](#previous-uri-session-middleware)
            - [Secure Policy Headers Middleware](#secure-policy-headers-middleware)
    - [Routing Boot](#routing-boot)
        - [Routing via Boot](#routing-via-boot)
        - [Domain Routing](#domain-routing)
        - [Route Handler](#route-handler)
        - [Route List Command](#route-list-command)
    - [Session Boot](#session-boot)
        - [Session Config](#session-config)
        - [Session Lifecycle](#session-lifecycle)
        - [Session Error Handling](#session-error-handling)
    - [Cookies Boot](#cookies-boot)
        - [Cookies Config](#cookies-config)
        - [Cookies Usage](#cookies-usage)
        - [Cookies Encryption](#cookies-encryption)
    - [Error Handler Boot](#error-handler-boot)
        - [Http Exceptions](#http-exceptions)
        - [Render Exception Views](#render-exception-views)
        - [Handle Other Exceptions](#handle-other-exceptions)
        - [Prioritize Error Handler](#prioritize-error-handler)
- [Credits](#credits)

---

Getting Started
===============

[](#getting-started)

Add the latest version of the app http project running this command.

```
composer require tobento/app-http

```

Requirements
------------

[](#requirements)

- PHP 8.4 or greater

Documentation
=============

[](#documentation)

App
---

[](#app)

Check out the [**App Skeleton**](https://github.com/tobento-ch/app-skeleton) if you are using the skeleton.

You may also check out the [**App**](https://github.com/tobento-ch/app) to learn more about the app in general.

Http Boot
---------

[](#http-boot)

The http boot does the following:

- PSR-7 implementations
- PSR-17 implementations
- installs and loads http config file
- base and current uri implementation
- http error handling implementation
- emits response

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

### Http Config

[](#http-config)

Check out `app/config/http.php` to change needed values.

### Request And Response

[](#request-and-response)

You may access the PSR-7, PSR-17 and PSR-18 interfaces by the app:

```
use Tobento\App\AppFactory;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use Psr\Http\Message\UriInterface;
use Tobento\App\Http\ResponseEmitterInterface;
use Tobento\App\Http\SimpleResponseEmitterInterface;
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-18 HTTP Client
$client = $app->get(ClientInterface::class);

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

// URI Services (all return 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 Factories
$requestFactory = $app->get(RequestFactoryInterface::class);
$responseFactory = $app->get(ResponseFactoryInterface::class);
$streamFactory = $app->get(StreamFactoryInterface::class);
$uploadedFileFactory = $app->get(UploadedFileFactoryInterface::class);
$uriFactory = $app->get(UriFactoryInterface::class);

// Response Emitters
$responseEmitter = $app->get(ResponseEmitterInterface::class);
$simpleResponseEmitter = $app->get(SimpleResponseEmitterInterface::class);

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

Check out the [**Uri Service**](https://github.com/tobento-ch/service-uri) to learn more about the base and current uri.

### Http Functions

[](#http-functions)

The following Http functions are available:

```
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)
```

### Swap PSR-7 And PSR-17 Implementation

[](#swap-psr-7-and-psr-17-implementation)

You might swap the PSR-7 and PSR-17 implementation to any alternative.
Check out the [**App - Customization**](https://github.com/tobento-ch/app#customization) to learn more about it.

Requester And Responser Boot
----------------------------

[](#requester-and-responser-boot)

The requester and responser boot does the following:

- [*RequesterInterface*](https://github.com/tobento-ch/service-requester) implementation
- [*ResponserInterface*](https://github.com/tobento-ch/service-responser) implementation and adds its middleware

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

Check out the [**Requester Service**](https://github.com/tobento-ch/service-requester) to learn more about it.

Check out the [**Responser Service**](https://github.com/tobento-ch/service-responser) to learn more about it.

**Responser Messages**

[Messages](https://github.com/tobento-ch/service-responser#messages) will be translated if you have installed the [App Message - Translating Messages](https://github.com/tobento-ch/app-message#translating-messages).

**Added Middleware**

ClassDescriptionTobento\\Service\\Responser\\Middleware\\Responser::classAdds the responser to the request attributes.Tobento\\Service\\Responser\\Middleware\\ResponserMergeInput::classMerges the responser input with the request input.Middleware Boot
---------------

[](#middleware-boot)

The middleware boot does the following:

- PSR-15 HTTP handlers (middleware) implementation
- dispatches middleware

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

Check out the [**Middleware Service**](https://github.com/tobento-ch/service-middleware) to learn more about the middleware implementation.

### Add Middleware via Config

[](#add-middleware-via-config)

You can configure middleware in the config file `app/config/middleware.php` which are applied to all routes and requests:

```
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(),
    ],
];
```

### Add Middleware via Boot

[](#add-middleware-via-boot)

You might create a boot for adding middleware:

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

### Middleware Aliases

[](#middleware-aliases)

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

**Add Aliases via Config**

You can configure middleware aliases in the config file `app/config/middleware.php`:

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

### Middleware Groups

[](#middleware-groups)

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

**Add Groups via Config**

You can configure middleware groups in the config file `app/config/middleware.php`:

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

### Available Middleware

[](#available-middleware)

#### Previous Uri Session Middleware

[](#previous-uri-session-middleware)

The `Tobento\App\Http\Middleware\PreviousUriSession::class` middleware is automatically added by the [Session Boot](#session-boot) which stores the uri history in the session.

**Get Previous Uri**

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

**Exclude From Previous Uri History**

You may exclude a certain uri from the history by adding a `X-Exclude-Previous-Uri` header on the response:

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

#### Secure Policy Headers Middleware

[](#secure-policy-headers-middleware)

This middleware will add the following secure policy headers to the response:

- `Strict-Transport-Security: max-age=31536000; includeSubDomains; preload`
- `X-Frame-Options: DENY`
- `X-Content-Type-Options: nosniff`
- `Referrer-Policy: same-origin`
- `Content-Security-Policy: base-uri 'none'; default-src 'self'; img-src 'self' data:; script-src 'nonce-***' 'self'; object-src 'none'; style-src 'nonce-***' 'self';`

In the `app/config/middleware.php` file:

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

**Using inline scripts and styles**

The middleware will add a `Content-Security-Policy` header with a nonce for `script-src` and `style-src`. Therefore, to allow inline scripts or styles you must add the nonce to the html:

If using the [App View](https://github.com/tobento-ch/app-view) bundle, you can retrieve the nonce from the view:

```
