Plain PHP templates render escaped values passed from a controller without embedding domain logic.
What It Does and When to Use It
Escape a variable in a plain PHP view. Controllers translate HTTP input to operations; domain services implement rules; templates render escaped output.
Requirements, Inputs and Expected Behavior
Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Use htmlspecialchars for text and attributes; avoid trusting raw HTML.
Example 1: Basic Operation
Escape a variable in a plain PHP view.
<?php
$view = ['name' => '<Ada>'];
ob_start();
echo '<h1>', htmlspecialchars($view['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'), '</h1>';
$html = ob_get_clean();
echo $html;
Example 2: Behavior and Validation
Choose templates from a fixed map instead of concatenating user input into a filename.
<?php
function render(string $view, array $data): string {
$allowed = ['home' => __DIR__ . '/views/home.php'];
if (!isset($allowed[$view])) throw new InvalidArgumentException('Unknown view');
extract($data, EXTR_SKIP);
ob_start();
try { require $allowed[$view]; return ob_get_clean(); }
catch (Throwable $e) { ob_end_clean(); throw $e; }
}
Practical Example: Application Use
Use PHP short echo tags and context-appropriate HTML escaping in a template.
<p><?= htmlspecialchars($title, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?></p>
Important Behavior and Edge Cases
The second example highlights: Choose templates from a fixed map instead of concatenating user input into a filename. The practical example adds: Use PHP short echo tags and context-appropriate HTML escaping in a template.
Comparison with Related Approaches
| Approach | What changes |
|---|---|
| Controller, service and template responsibilities | Controllers translate HTTP input to operations; domain services implement rules; templates render escaped output. |
| Choosing safely | Treat template names, route parameters and user data as separate trust domains. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Assuming successful execution proves the result is usable | Check the return value, required extension, and observable output of the specific operation. |
| Ignoring runtime and environment differences | Verify PHP version, SAPI, operating system, service access, and permissions before deployment. |
| Skipping operational constraints | Use htmlspecialchars for text and attributes; avoid trusting raw HTML. |
Key Takeaways
- Plain PHP templates render escaped values passed from a controller without embedding domain logic.
- Use PHP short echo tags and context-appropriate HTML escaping in a template.
- Treat template names, route parameters and user data as separate trust domains.