How can the separation of business logic and presentation be achieved in PHP code, especially when dealing with HTML output?
Separating business logic from presentation in PHP code can be achieved by using a templating engine like Twig. This allows you to keep your PHP code (business logic) separate from your HTML output (presentation), making your code more organized and easier to maintain.
// Using Twig for separating business logic and presentation
require_once 'vendor/autoload.php';
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);
$data = [
'title' => 'Welcome to my website',
'content' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
// other data needed for the template
];
echo $twig->render('index.html', $data);
Related Questions
- What PHP function can be used to search for specific words in a text and return their position?
- How can troubleshooting steps be taken to resolve issues where PHP files are not being parsed and instead trigger a download dialog in Apache?
- What are some best practices for optimizing PHP MySQL queries for performance?