Frontends based on xp-forge/web
.
Frontend uses 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.
class Home {
#[@get, @$param: param('name')]
public function get($param) {
return ['name' => $param ?: 'World'];
}
}
For the above class, the template engine will receive home as template name and the returned map as context. The implementation below uses the xp-forge/handlebars library to transform the templates.
use com\handlebarsjs\{HandlebarsEngine, FilesIn};
use io\Path;
use web\frontend\Templates;
class TemplateEngine implements Templates {
private $backing;
public function __construct(Path $templates) {
$this->backing= (new HandlebarsEngine())->withTemplates(new FilesIn($templates));
}
public function write($name, $context, $out) {
$this->backing->write($this->backing->load($name), $context, $out);
}
}
The handlebars template is quite straight-forward:
Finally, wiring it together is done in the application class, as follows:
use web\Application;
use web\frontend\{Frontend, Templates};
use web\handler\FilesFrom;
use io\Path;
class Site extends Application {
/** @return [:var] */
protected function routes() {
$files= new FilesFrom(new Path($this->environment->webroot(), 'src/main/webapp'));
$templates= new TemplateEngine(new Path($this->environment->webroot(), 'src/main/handlebars'));
return [
'/favicon.ico' => $files,
'/static' => $files,
'/' => new Frontend(new Home(), $templates)
];
}
}
To run it, use xp -supervise web Site
, which will serve the site at http://localhost:8080/. Find and clone the example code here.