How can PHP code be structured to efficiently handle database queries and template rendering?
To efficiently handle database queries and template rendering in PHP, it is recommended to separate concerns by using a model-view-controller (MVC) architecture. This involves creating separate classes or functions for handling database queries (model), rendering templates (view), and controlling the flow of the application (controller). By structuring your code in this way, you can improve code organization, reusability, and maintainability.
// Example of a simple MVC structure in PHP
// Model - Handles database queries
class Database {
public function query($sql) {
// Code to execute database query
}
}
// View - Renders templates
class Template {
public function render($template, $data) {
// Code to render template with data
}
}
// Controller - Controls application flow
class Controller {
public function index() {
$db = new Database();
$data = $db->query("SELECT * FROM table");
$template = new Template();
$template->render("index.php", $data);
}
}
// Usage
$controller = new Controller();
$controller->index();