PHPackages                             xp-forge/frontend - 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. [Templating &amp; Views](/categories/templating)
4. /
5. xp-forge/frontend

ActiveLibrary[Templating &amp; Views](/categories/templating)

xp-forge/frontend
=================

Web Frontends

v7.2.0(9mo ago)147.5k—7.1%12BSD-3-ClausePHPPHP &gt;=7.4.0CI passing

Since Apr 2Pushed 3mo ago1 watchersCompare

[ Source](https://github.com/xp-forge/frontend)[ Packagist](https://packagist.org/packages/xp-forge/frontend)[ Docs](http://xp-framework.net/)[ RSS](/packages/xp-forge-frontend/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (8)Versions (54)Used By (2)

Web frontends
=============

[](#web-frontends)

[![Build status on GitHub](https://github.com/xp-forge/frontend/workflows/Tests/badge.svg)](https://github.com/xp-forge/frontend/actions)[![XP Framework Module](https://raw.githubusercontent.com/xp-framework/web/master/static/xp-framework-badge.png)](https://github.com/xp-framework/core)[![BSD Licence](https://raw.githubusercontent.com/xp-framework/web/master/static/licence-bsd.png)](https://github.com/xp-framework/core/blob/master/LICENCE.md)[![Requires PHP 7.4+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-7_4plus.svg)](http://php.net/)[![Supports PHP 8.0+](https://raw.githubusercontent.com/xp-framework/web/master/static/php-8_0plus.svg)](http://php.net/)[![Latest Stable Version](https://camo.githubusercontent.com/792d07958da1546386370292b3a572a09e75c7ebef415347318e40338b841c4d/68747470733a2f2f706f7365722e707567782e6f72672f78702d666f7267652f66726f6e74656e642f76657273696f6e2e737667)](https://packagist.org/packages/xp-forge/frontend)

Frontends based on `xp-forge/web`, using annotation-based routing.

Example
-------

[](#example)

Frontend uses handler classes with methods annotated with HTTP verbs to handle routing. These methods return a context, which is passed along with the template name to the template engine.

```
use web\frontend\{Handler, Get, Param};

#[Handler]
class Hello {

  #[Get]
  public function greet(#[Param('name')] $param) {
    return ['name' => $param ?: 'World'];
  }
}
```

*Note: For PHP 7, the `Param` annotation must be on a line by itself, [see here](https://gist.github.com/thekid/8ce84b0d0de8fce5b6dd5faa22e1d716#file-home-class-php)!*

For the above class, the template engine will receive *home* as template name and the returned map as context. This library contains only the skeleton for templating - the [xp-forge/handlebars-templates](https://github.com/xp-forge/handlebars-templates) library implements it. For the rest of the examples, we'll be using it.

The handlebars template *hello.handlebars* (calculated from the lowercase version of the above handler class' name) is quite straight-forward:

```
DOCTYPE html>

  Hello World

  Hello {{name}}

```

Finally, wiring it together is done in the application class, as follows:

```
use web\Application;
use web\frontend\{AssetsFrom, Frontend, Handlebars};

class Site extends Application {

  /** @return [:var] */
  public function routes() {
    $assets= new AssetsFrom($this->environment->path('src/main/webapp'));
    $templates= new Handlebars($this->environment->path('src/main/handlebars'));

    return [
      '/favicon.ico' => $assets,
      '/static'      => $assets,
      '/'            => new Frontend(new Hello(), $templates)
    ];
  }
}
```

To run it, use `xp -supervise web Site`, which will serve the site at .

Organizing your code
--------------------

[](#organizing-your-code)

In real-life situations, you will not want to put all of your code into the `Hello` class. In order to separate code out into various classes, place all handler classes inside a dedicated package:

```
@FileSystemCL
package org.example.web {

  public class org.example.web.Home
  public class org.example.web.User
  public class org.example.web.Group
}
```

Then use the delegation API provided by the `HandlersIn` class:

```
use web\frontend\{Frontend, HandlersIn};

// ...inside the routes() method, as seen above:
new Frontend(new HandlersIn('org.example.web'), $templates);
```

Handling routes and methods
---------------------------

[](#handling-routes-and-methods)

The `Handler` annotation can include a path which is used as a prefix for all method routes in a handler class. Placeholders can be used to select method parameters from the request URI.

```
use web\frontend\{Handler, Get};

#[Handler('/hello')]
class Hello {

  #[Get]
  public function world() {
    return ['greet' => 'World'];
  }

  #[Get('/{name}')]
  public function person(string $name) {
    return ['greet' => $name];
  }
}
```

The above method routes will only accept `GET` requests. `POST` request methods can be annotated with `Post`, `PUT` with `Put`, and so on. To overwrite the method used for POST requests, pass the special `_method` field:

```

```

This will route the request as if it had been issued as `PUT /example HTTP/1.1`.

### Views

[](#views)

Route methods can return `web.frontend.View` instances to have more control over the response:

```
use web\frontend\View;

// Equivalent of the above world() method's return value
return View::named('hello')->with(['greet' => 'World']);

// Redirecting to either paths or absolute URIs
return View::redirect('/hello/World');

// No content
return View::empty()->status(204);

// Add headers and caching, here: for 7 days
return View::named('blog')
  ->with($article)
  ->header('X-Binford', '6100 (more power)')
  ->modified($modified)
  ->cache('max-age=604800, must-revalidate')
;
```

Serving assets
--------------

[](#serving-assets)

Assets are delivered by the `AssetsFrom` handler as seen above. It takes care of content types, handling conditional and range requests for partial content, as well as compression.

### Sources

[](#sources)

The constructor accepts single paths as well as an array of paths which will be searched for the requested asset. The first path to provide the asset is selected, the file being served from there.

```
use web\frontend\AssetsFrom;

// Single source
$assets= new AssetsFrom($this->environment->path('src/main/webapp'));

// Multiple sources
$assets= new AssetsFrom([
  $this->environment->path('src/main/webapp'),
  $this->environment->path('vendor/example/layout-lib/src/main/webapp'),
]);
```

### Caching

[](#caching)

Assets can be delivered with a `Cache-Control` header by passing it to the `with` function. In this example, assets are cached for 28 days, but clients are asked to revalidate using conditional requests before using their cached copy.

```
use web\frontend\AssetsFrom;

$assets= (new AssetsFrom($path))->with([
  'Cache-Control' => 'max-age=2419200, must-revalidate'
]);
```

### Compression

[](#compression)

Assets can also be delivered in compressed forms to save bandwidth. The typical bundled JavaScript library can be megabytes in raw size! By using e.g. Brotli, this can be drastically reduced to a couple of hundred kilobytes.

- The request URI is mapped to the asset file name
- If the clients sends an `Accept-Encoding` header, it is parsed and the client preference negotiated
- The server tries *\[file\]*.br (for Brotli), *\[file\]*.bz2 (for BZip2), *\[file\]*.gz (for GZip) and *\[file\]*.dfl (for Deflate), and only sends the uncompressed version if none exists nor is acceptable.

*Note: Assets are not compressed on the fly as this would cause unnecessary server load.*

### Asset fingerprinting

[](#asset-fingerprinting)

Generated assets can be fingerprinted by embedding a version identifier in the filename, e.g. *\[file\].\[version\].\[ext\]*. Every time their contents change, the version (or *fingerprint*) changes, and with it the filename. These assets can then be regarded "immutable", and served with an "infinite" maximum age. Bundlers (like Webpack or the one built-in to this library) will create an *asset manifest* along with these assets.

```
use web\frontend\{AssetsFrom, AssetsManifest};

$manifest= new AssetsManifest($path->resolve('manifest.json'));
$assets= new AssetsFrom($path)->with(fn($uri) => [
  'Cache-Control' => $manifest->immutable($uri) ?? 'max-age=2419200, must-revalidate'
]);
```

Because mapping the filenames happens in the template engine, the manifest must also be passed there:

```
use web\frontend\Handlebars;
use web\frontend\helpers\Assets;

$templates= new Handlebars($path, [new Assets($manifest)]);
```

The handlebars code then uses the *asset* helper to lookup the filename including the fingerprint:

```

```

*This way, we don't have to commit changes to our handlebars file every time the assets are changed, which may happen often!*

### The built-in bundler

[](#the-built-in-bundler)

Bundling assets makes sense from a security standpoint, but also to reduce HTTP requests. This library comes with a `bundle` subcommand, which can generate JavaScript and CSS bundles from dependencies tracked in `package.json`.

```
{
  "dependencies": {
    "simplemde": "^1.11",
    "transliteration": "^2.1"
  },
  "bundles": {
    "vendor": {
      "simplemde": "dist/simplemde.min.js | dist/simplemde.min.css",
      "transliteration": "dist/browser/bundle.umd.min.js"
    }
  }
}
```

To create the bundles to the *src/main/webapp/static* directory and the assets manifest, run the following:

```
$ xp bundle -m src/main/webapp/manifest.json src/main/webapp/static
# ...
```

This will create *vendor.\[fingerprint\].js* and *vendor.\[fingerprint\].css* files as well as compressed versions (*if the zlib and [brotli](https://github.com/kjdev/php-ext-brotli) PHP extensions are available*) and the assets manifest, which maps the file names without fingerprints to those with.

The bundler can also resolve local files, URLs as well as [Google fonts](https://fonts.google.com/):

```
{
  "bundles": {
    "vendor": {
      "src/main/js": "index.js",
      "https://cdn.amcharts.com/lib/4": "core.js | charts.js | themes/kelly.js",
      "fonts://display=swap": "Overpass"
    }
  }
}
```

Error handling
--------------

[](#error-handling)

By default, errors and exceptions will yield in a minimalistic error page with the corresponding error code (*defaulting to 500 Internal Server Error*) shown. Exceptions can be handled by a closure, a status code or by default, and decide to return a view of their own. This view is loaded from the *errors/* subfolder and passed a context of `['cause' => $exception]`.

```
use web\frontend\{HandlersIn, Frontend, Exceptions};
use org\example\{InvalidOrder, LinkExpired};
use lang\Throwable;

$frontend= (new Frontend(new HandlersIn('org.example.web'), $templates))
  ->handling((new Exceptions())
    ->catch(InvalidOrder::class, fn($e) => View::error(503, 'invalid-order')),
    ->catch(LinkExpired::class, 404) // uses template "errors/404"
    ->catch(Throwable::class)        // "errors/{status}" for web.Error, "errors/500" for others
  )
;
```

Using our handlebars engine from above, the template *errors/404.handlebars* could look like this:

```
DOCTYPE html>

  Error 404

  Not found
  {{cause.message}}

  {{! Log errors !}}
  {{log request.uri "~" cause level="error"}}

```

Security
--------

[](#security)

This library sets the following security header defaults:

- `X-Content-Type-Options: nosniff` - prevents browsers from [MIME sniffing](https://mimesniff.spec.whatwg.org/)
- `X-Frame-Options: DENY` - prevents site from being embedded in an ``.
- `Referrer-Policy: no-referrer-when-downgrade` - doesn't send HTTP referrer over unencrypted connections.

To configure framing, referrer and content security policies, use the *security()* fluent interface:

```
use web\frontend\{Frontend, Security};

$policy= (new Security())
  ->framing('SAMEORIGIN')
  ->referrers('strict-origin')
  ->csp([
    'default-src' => '"none"',
    'script-src'  => ['"self"', '"nonce-{{nonce}}"', 'https://example.com'],
    // etcetera
  ])
;
$frontend= (new Frontend($delegates, $templates))->enacting($policy);
```

For static assets, the same policy can be used:

```
use web\frontend\{AssetsFrom, Security};

$policy= /* see above */
$assets= (new AssetsFrom($path))->enacting($policy);
```

The default configuration is to set `script-src 'none'; object-src 'none'`, see

*Read more about hardening response headers at  or watch this talk: *

Performance
-----------

[](#performance)

When using the production servers, the application's code is only compiled and its setup only runs once. This gives us lightning-fast response times:

[![Network console screenshot](https://private-user-images.githubusercontent.com/696742/440185336-0310304b-23f8-43c9-8809-95a805fede4f.png?jwt=eyJ0eXAiOiJK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aQSUyRjIwMjYwNDA1JTJGdXMtZWFzdC0xJTJGczMlMkZhd3M0X3JlcXVlc3QmWC1BbXotRGF0ZT0yMDI2MDQwNVQwNTMyNDNaJlgtQW16LUV4cGlyZXM9MzAwJlgtQW16LVNpZ25hdHVyZT1lNzU1YzI2ODFhNzZiZTkzMzhkYjZhNzQxOWQ5ODUwNTJhNmY3M2I0MTNjNGE2MmZhN2UyMjI5YzI3M2EyMmExJlgtQW16LVNpZ25lZEhlYWRlcnM9aG9zdCJ9.G06tWam7CDvfrVuwulBb6--05kW1ENjCKMKxv9ptrdo)

###  Health Score

52

—

FairBetter than 96% of packages

Maintenance72

Regular maintenance activity

Popularity30

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 99.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~52 days

Recently: every ~59 days

Total

52

Last Release

276d ago

Major Versions

v2.3.1 → v3.0.02021-04-10

v3.8.0 → v4.0.02022-10-29

v4.3.0 → v5.0.02023-07-22

v5.6.0 → v6.0.02023-12-25

v6.4.0 → v7.0.02025-05-04

PHP version history (3 changes)v0.1.0PHP &gt;=5.6.0

v2.0.0PHP &gt;=7.0.0

v7.0.0PHP &gt;=7.4.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/07d18d882c8b4aaf3466432f64018214f2771eda333202175431ee7233795376?d=identicon)[thekid](/maintainers/thekid)

---

Top Contributors

[![thekid](https://avatars.githubusercontent.com/u/696742?v=4)](https://github.com/thekid "thekid (397 commits)")[![johannes85](https://avatars.githubusercontent.com/u/470531?v=4)](https://github.com/johannes85 "johannes85 (1 commits)")

---

Tags

annotationsassetsasyncbrotlibundlercachingcompressioncontent-security-policycsrf-tokensfingerprintingfrontendgzipimmutablephp7php8template-enginewebxp-frameworkzstandardmodulexp

### Embed Badge

![Health badge](/badges/xp-forge-frontend/health.svg)

```
[![Health](https://phpackages.com/badges/xp-forge-frontend/health.svg)](https://phpackages.com/packages/xp-forge-frontend)
```

###  Alternatives

[xp-framework/compiler

XP Compiler

2026.0k9](/packages/xp-framework-compiler)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
