Pass Controller Data to a PHP MVC View

In a small PHP MVC application, the front controller selects an action, the controller reads and validates the request, and the model performs the calculation or data operation. The controller then passes an explicit data array to the view instead of relying on unrelated globals or a second include path.

Last updated: October 10, 2026.

<?php
final class CalculatorController
{
    public function show(): void
    {
        $left = filter_input(INPUT_POST, 'left', FILTER_VALIDATE_FLOAT);
        $right = filter_input(INPUT_POST, 'right', FILTER_VALIDATE_FLOAT);

        $view = ['result' => null, 'error' => null];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if ($left === false || $right === false || $left === null || $right === null) {
                $view['error'] = 'Enter two valid numbers.';
            } else {
                $view['result'] = $left + $right;
            }
        }

        require __DIR__ . '/views/calculator.php';
    }
}

The required template runs in the method scope and can read $view. Escape values when generating HTML, even when the current result is numeric, so the view keeps a consistent output rule.

Keep one request flow in charge

The front controller should create the controller and call show() once. Avoid including a controller file from the template or rendering the same template before the POST branch computes its result. PHP documents that require inherits the variable scope of the line on which it is called, which is why the view can access the local $view array.

For a larger application, wrap rendering in a dedicated method such as render($template, $data). Keep the data contract explicit and use descriptive keys rather than extracting arbitrary request variables into the template scope.

Validate input before calling the model

The PHP filter_input documentation explains that validation can return false and that a missing variable returns null unless flags change that behavior. Check both outcomes. For database work, the controller should pass validated values to a model or service that uses parameterized queries.

Do not put SQL, redirects, and presentation markup into one template. Clear boundaries make errors easier to test and prevent a view refresh from accidentally repeating a write. Continue with secure form processing, calling server routes from a page, and preventing duplicate submissions.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov