Search by

trypoint / php-view

madalinmariusstan

Native PHP templates with automatic immutable ViewValue wrapping, fluent transformations, context-aware escaping, layouts, snippets and secure template resolution. PSR-7 and PSR-17 ready.

Package info

github.com/trypoint/php-view

pkg:composer/trypoint/php-view

Statistics

Installs: 12

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0-beta.1 2026-11-28 20:32 UTC

This package is auto-updated.

Last update: 2026-11-28 20:34:44 UTC


README

Introduction

Point PHP-View renders native PHP templates into PSR-7 responses. It follows Slim PHP-View's small, practical surface but adds immutable, context-aware ViewValue objects for template data.

Templates are plain PHP files. There is no compiler, template language, mandatory framework or container. Point Framework integration is optional.

Requirements

  • PHP >= 8.4.27 with ext-mbstring.
  • A PSR-7 / PSR-17 implementation supplied by the application.

The library depends only on psr/http-message and psr/http-factory.

Installation

Install the published alpha from Packagist:

composer require trypoint/php-view:0.1.0-beta.1

Quick start

<?php

use Point\View\View;

require __DIR__ . '/vendor/autoload.php';

$view = View::fromPaths(__DIR__ . '/templates');

// In a PSR-7 route handler:
return $view->render($response, 'home', [
    'title' => 'Hello, World!',
]);

templates/home.php:

<h1><?= $title->esc() ?></h1>

Template names omit .php. Use pages/about for subpaths and admin::dashboard for configured namespaces.

Usage with Point Framework

Install Point with composer require trypoint/point when using this integration.

use Point\Factory\AppFactory;
use Point\View\Integration\ViewMiddleware;
use Point\View\View;

$app = AppFactory::create();
$view = View::fromPaths(__DIR__ . '/templates');
$app->add(new ViewMiddleware($view));

$app->get('/', function ($request, $response) {
    return $request->getAttribute('view')->render($response, 'home', [
        'title' => 'Home',
    ]);
});

ViewMiddleware puts the view in the view request attribute. Pass another name as the second constructor argument if needed.

Standalone usage

Install the PSR-7 / PSR-17 implementation used in this example with composer require httpsoft/http-message and load Composer's autoloader as in the quick start.

use HttpSoft\Message\ResponseFactory;
use Point\View\View;

$view = View::fromPaths(__DIR__ . '/templates');

$response = $view->renderResponse(new ResponseFactory(), 'home', [
    'title' => 'Standalone',
], 200, [
    'Content-Type' => 'text/html; charset=UTF-8',
]);

Use render() for an existing PSR-7 response and renderToString() when you need a string.

Rendering

ViewInterface exposes render() and renderToString(). The concrete View also creates PSR-17 responses with renderResponse(). Use share() for defaults, shared() to read them, and hasTemplate() or resolver() to inspect template availability. Per-render data overrides shared values. Keep request-specific data out of shared defaults on long-lived views.

render() requires a writable body. Non-empty output also requires a seekable body and is appended at EOF, regardless of the current cursor. The returned response drops stale Content-Length and retains the status, other headers and shared body stream. An empty render leaves the cursor and headers intact. Set your own Content-Type. A failed write may leave partial output.

Fluent template variables

Each top-level value is wrapped in an immutable ViewValue. Transformations return new wrappers, and referenced objects can still be mutable. Implicit string conversion uses the wrapper's escape context, which defaults to HTML.

<h1><?= $title->esc() ?></h1>
<p><?= $description->trim()->excerpt(150)->esc() ?></p>
<?= $this->get('subtitle', 'Welcome')->upper()->esc() ?>
  • Transform with upper(), lower(), trim(), excerpt($length, $suffix, $preserveWords) or or($fallback). The fallback applies to null, an empty string or an empty array.
  • Inspect with length(), isEmpty(), isNull(), isTruthy(), value() or context(). Use withContext() to change the escape context of a wrapper. ViewValue::of() accepts plain values and returns existing wrappers as supplied.
  • Strings, numbers, booleans, null, backed enums, Stringable objects and dates can be stringified. For arrays and plain objects, use value(), json() or js().
  • Inside templates, $this is a TemplateContext. Use get(), has() and all() for data, value() to wrap a separate value, and e() or escape() to wrap and escape it.

Use PHP identifiers for data keys. The names this, GLOBALS, __path and __data are reserved, including case variants.

Layouts, snippets and sections

In templates/home.php:

<?php $this->layout('default'); ?>
<h1><?= $title->esc() ?></h1>
<?php $this->start('sidebar'); ?>
<aside><?= $title->esc() ?></aside>
<?php $this->end(); ?>
<?= $this->snippet('header') ?>

In templates/layouts/default.php:

<!doctype html>
<html><body><?= $content->raw() ?><?= $this->section('sidebar') ?></body></html>
  • layout() selects a file under layouts/ and overrides the constructor's defaultLayout. An empty name opts out. The layout receives reserved content as a ViewValue. Layouts and snippets cannot declare a layout.
  • snippet() looks under snippets/, inherits template data and accepts overrides as its second argument. Snippets share sections and can nest up to 64 calls deep.
  • End sections in the template that started them. startSection() and endSection() are aliases. The last completed section with the same name wins. section() accepts an optional default string. Section output is already rendered markup and belongs to the current render.

Namespaces and URL generation

Pass a resolver to configure namespaces. Each named or unnamed group searches its roots in order. Layout and snippet prefixes preserve the namespace, so $this->snippet('admin::nav') loads snippets/nav.php in the admin roots.

use Point\View\TemplateResolver;
use Point\View\View;

$view = new View(new TemplateResolver(
    [__DIR__ . '/templates'],
    ['admin' => __DIR__ . '/admin/templates'],
));
$html = $view->renderToString('admin::dashboard', $data);

The View constructor also accepts layout and snippet prefixes, a default escape context, and a urlGenerator closure. The closure takes a route name, parameter array and absolute flag for $this->url(). With Point, delegate to its UrlGeneratorInterface::urlFor() using raw route parameters. Build absolute origins from trusted application configuration.

Escaping and security

Deploy templates from directories you control. They run as PHP with application privileges. Encode untrusted data for the output location.

Output Method
HTML text esc()
Quoted HTML attribute attr()
Inline JavaScript literal js()
CSS declaration value css()
URL component url()
JSON payload json()
Trusted, already-rendered markup raw()

Quote HTML attributes that contain dynamic values, for example title="<?= $title->attr() ?>". Use esc() with an explicit EscapeContext to select an output context. Restrict CSS values and complete URLs to what your application allows. js() hex-escapes HTML-sensitive characters in its JSON literal. raw() emits the underlying string without sanitizing it.

Relative template names are limited to 255 bytes and use letters, digits, underscore, dash, dot and slash. Absolute paths, stream wrappers, empty segments and traversal segments are rejected. Each lookup checks freshness, readability and canonical containment, including symlinks. Control write access to roots because a filesystem change between lookup and inclusion can affect the result.

Leave renderer-owned buffers intact. A deliberately closed or non-removable buffer can prevent recovery, and already-emitted output cannot be recalled. Report vulnerabilities privately through SECURITY.md.

Exceptions

Exception Meaning
InvalidArgumentException Invalid configuration or data key.
InvalidTemplateNameException Invalid template name or unknown namespace.
TemplateNotFoundException The template could not be resolved in the configured roots.
RenderException Template execution or stream failure. Exceptions wrapped by the renderer retain the original cause.
UnsupportedValueException The value could not be stringified or encoded.

Library-specific exceptions extend ViewException. Use production error handling to protect internal paths and application details.

Migrating from Slim PHP-View

Replace new PhpRenderer($dir) with View::fromPaths($dir). Omit the extension when calling render(), replace fetch() with renderToString(), and use share() for defaults. Layout selection and template values follow the examples above.

Testing

From a source checkout:

composer install
composer test:all

See CONTRIBUTING.md for contribution guidance.

License

MIT.