Documentation · Chapter 03

Pass data
to the view.

A page becomes useful when the controller gives it values. We keep preparation separate from display.

You will change one element at a time, in an exact file, then verify the result.

The controller prepares

Replace only the index() method of AboutController. The second view() argument is an associative array: every key becomes a name available in the view.

phpaml — zsh
public function index(Request $request): Response
{
    return $this->view('about.php', [
        'projectName' => 'Reading List',
        'bookCount' => 3,
    ]);
}
projectName

name used by the view

Reading List

value prepared by the controller

The view displays without blindly trusting

src/views/about.php

phpaml — zsh
<main>
    <h1><?= htmlspecialchars($projectName, ENT_QUOTES, 'UTF-8') ?></h1>
    <p>You track <?= (int) $bookCount ?> books.</p>
</main>

<?= ... ?> is a short form of echo. htmlspecialchars converts characters that could be interpreted as HTML. This protection matters whenever a value may come from a form, URL, or database. The (int) cast guarantees a number here.

Follow the value

1Controller'bookCount' => 3
→
2view()about.php
→
3View$bookCount
→
4HTML3 books

The view does not fetch data itself. The controller gives it data explicitly, making the flow readable and testable.

BEGINNER QUESTIONS

Normal questions at this stage.

Why not write the number directly in the view?

Because a real value will change. Passing it prepares the code for service or database data.

Can I pass an object?

Yes. The initial project already passes a HomeModel to home.php.

Must every text be escaped?

Escape dynamic values displayed in HTML, especially those coming from users or external sources.