The essentials

PHP object views

An object view receives typed data through its constructor and renders HTML when invoked. This is one way to implement the view in MVC. You can use another template engine while keeping the same controller and model boundaries.

On this page

A complete view

Save this as hello.php and run php hello.php with PHP 8.3–8.6:

php
<?php

declare(strict_types=1);

final class Greeting
{
    public function __construct(private string $name) {}

    public function __invoke(): void
    {
        ?>
<p>Hello, <?= htmlspecialchars($this->name, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8") ?>.</p>
        <?php
    }
}

(new Greeting("<reader> & friend"))();

The constructor makes the required input visible to PHP and your editor. __invoke() lets the object be called as a function. The browser displays <reader> & friend as text because the value is escaped at the HTML output boundary.

Prepare data before rendering

The controller obtains the data and passes it to the view. The view formats that data; it does not query the model or call DI to acquire missing dependencies.

Escape dynamic values where they enter HTML text or quoted attributes. Other contexts, such as JavaScript or an arbitrary URL, require their own encoding or validation.

Compose a page

A layout renders the document shell around a child view. In the application example, an abstract View declares the shared __invoke(): void contract. Layout accepts a View and renders it inside <main>.

The controller can then express the complete rendering in one line:

php
<?php

(new Layout($article->title))(new ArticlePage($article));

This line uses the application's loaded classes and article. A base class is useful for that composition, but the standalone greeting above needs none.