Separating controllers and views keeps request processing independent of HTML rendering.
What It Does
Separating controllers and views keeps request processing independent of HTML rendering. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
$routes = ['GET /items' => fn () => 'list', 'POST /items' => fn () => 'create'];
$key = 'GET /items';
echo isset($routes[$key]) ? $routes[$key]() : '404';
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
$path = parse_url('/items/17?view=short', PHP_URL_PATH);
if (preg_match('~^/items/(?P<id>\d+)$~D', $path, $m)) echo (int) $m['id'];
Practical Example: Putting It to Use
Controllers prepare data and views perform context-appropriate escaping.
<?php
$controllerData = ['name' => '<Admin>'];
$view = '<h2>' . htmlspecialchars($controllerData['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '</h2>';
echo $view;
Important Behavior and Edge Cases
Escape dynamic values at the view boundary and avoid database access in templates.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Separating Controllers and Views | Separating controllers and views keeps request processing independent of HTML rendering. |
| Related approach | A front controller or router maps requests to controller actions. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Separating Controllers and Views | Escape dynamic values at the view boundary and avoid database access in templates. |
| Assuming a related mechanism has the same behavior | A front controller or router maps requests to controller actions. |
Key Takeaways
- Separating controllers and views keeps request processing independent of HTML rendering.
- Escape dynamic values at the view boundary and avoid database access in templates.
- A front controller or router maps requests to controller actions.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.