Skip to content

Repository files navigation

InitPHP Views

A small, adapter-based view rendering layer for PHP. Write your application against one tiny interface and render with plain PHP, Blade or Twig — switching engines is a one-line change.

CILatest Stable VersionTotal DownloadsLicensePHP Version Require

Requirements

  • PHP 8.0 or higher

The bundled adapters need their engine only when you use them:

AdapterClassEngineNeeds
Pure PHPInitPHP\Views\Adapters\PurePHPAdapterPlain .php templates— (core only)
BladeInitPHP\Views\Adapters\BladeAdapterLaravel Bladeilluminate/view
TwigInitPHP\Views\Adapters\TwigAdapterSymfony Twigtwig/twig

Installation

composer require initphp/views

Then install the engine for the adapter you want (skip this for the Pure PHP adapter):

composer require illuminate/view # for BladeAdapter
composer require twig/twig # for TwigAdapter

Quick start

Register an adapter once through the View facade, then render from anywhere with the global view() helper.

require'vendor/autoload.php';
useInitPHP\Views\Facade\View;
useInitPHP\Views\Adapters\PurePHPAdapter;
View::via(newPurePHPAdapter(__DIR__ . '/views'));
echoview('dashboard', ['username' => 'admin']);

views/dashboard.php:

<h1>Welcome, <?=htmlspecialchars($username) ?></h1>

Rendering multiple views

Pass a list of names to render them in order and concatenate the output:

echoview(['header', 'content', 'footer'], ['title' => 'Home']);

Passing data

$data is an associative array, or an object whose public properties are used:

$user = newstdClass();
$user->username = 'admin';
echoview('profile', $user);

The view() helper and the View facade

The view() helper is a thin wrapper over the facade:

function view(string|array$views, array|object$data = []): string;

It queues the views, attaches the data and renders — equivalent to:

echo View::setView('header', 'footer')->setData(['title' => 'Home'])->render();

Every call you make on View is forwarded to the registered adapter:

CallReturnsPurpose
View::via(string|ViewAdapterInterface $adapter)voidRegister the adapter that backs the facade.
View::setView(string ...$views)adapterQueue one or more views, in order.
View::setData(array|object $data)adapterMerge data exposed to the views.
View::getData(?string $key = null, mixed $default = null)mixedRead merged data (or everything when $key is null).
View::render()stringRender the queue and return the output.

View::via() accepts a ready-made adapter instance, or the class name of an adapter that can be built with no constructor arguments. Calling the facade before an adapter is registered throws a ViewException.

Adapters

Pure PHP adapter

Renders ordinary .php files. The .php extension is added automatically when missing, and each file is evaluated in an isolated scope: it receives the data as local variables and has no access to the adapter instance ($this).

useInitPHP\Views\Facade\View;
useInitPHP\Views\Adapters\PurePHPAdapter;
View::via(newPurePHPAdapter(__DIR__ . '/views'));
echoview('dashboard/index', ['username' => 'admin']);

A missing view file throws a ViewException.

Blade adapter

Bootstraps a standalone Blade engine — no full Laravel application required. Install illuminate/view first.

useInitPHP\Views\Facade\View;
useInitPHP\Views\Adapters\BladeAdapter;
View::via(newBladeAdapter(__DIR__ . '/views', __DIR__ . '/cache'));
echoview('dashboard', ['username' => 'admin']);

Both directories must exist. The first argument may also be an array of template directories. Register custom directives and conditionals on the adapter instance:

$blade = newBladeAdapter(__DIR__ . '/views', __DIR__ . '/cache');
View::via($blade);
$blade->directive('datetime', staticfunction (string$expression): string {
return"<?php echo ($expression)->format('Y-m-d H:i'); ?>";
});
$blade->if('admin', staticfn ($user): bool => $user->isAdmin());

The adapter also exposes the most common factory methods — make(), file(), exists(), share(), composer(), creator(), addNamespace() and replaceNamespace() — and forwards any other call to the underlying Blade factory. See the Blade documentation.

Twig adapter

Bootstraps a Twig environment. Install twig/twig first.

useInitPHP\Views\Facade\View;
useInitPHP\Views\Adapters\TwigAdapter;
View::via(newTwigAdapter(__DIR__ . '/views', __DIR__ . '/cache'));
echoview('dashboard.html.twig', ['username' => 'admin']);

Both directories must exist. Twig does not add a file extension, so include it in the view name. Use getEnvironment() to add extensions, globals or filters:

$twig = newTwigAdapter(__DIR__ . '/views', __DIR__ . '/cache');
$twig->getEnvironment()->addGlobal('app_name', 'InitPHP');
View::via($twig);

Exceptions

All exceptions implement InitPHP\Views\Exceptions\ViewExceptionInterface, so a single catch can handle every failure this package raises.

ExceptionExtendsThrown when
ViewExceptionRuntimeExceptionThe facade is used before an adapter is registered, or a view file is missing.
ViewAdapterExceptionViewExceptionView::via() is given an invalid adapter.
ViewInvalidArgumentExceptionInvalidArgumentExceptionA view or cache directory does not exist.
useInitPHP\Views\Exceptions\ViewExceptionInterface;
try {
echoview('dashboard', $data);
} catch (ViewExceptionInterface$e) {
// handle any InitPHP Views failure
}

Custom adapters

Implement InitPHP\Views\Interfaces\ViewAdapterInterface (or extend AdapterAbstract, which already handles queueing and data) and register it with View::via(). See docs/custom-adapter.md.

Documentation

Full developer documentation lives in docs/:

Contributing

Bug reports and pull requests are welcome. Please read the org-wide contribution guide first. Run the full check suite locally before opening a PR:

composer ci # php-cs-fixer (dry-run) + phpstan + phpunit

Credits

License

Released under the MIT License. Copyright © 2022 InitPHP.

About

Small, adapter-based view rendering layer for PHP 8: render with plain PHP, Blade or Twig behind one interface.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages