Skip to content
PHP Logo

What are the best practices for separating concerns in PHP code, particularly when dealing with database operations and HTML output?

Separating concerns in PHP code involves dividing different functionalities into separate modules or classes to improve code readability, reusability, and maintainability. When dealing with database operations and HTML output, it's recommended to use the MVC (Model-View-Controller) design pattern. The Model handles database operations, the View generates HTML output, and the Controller acts as an intermediary between the Model and View.

php
// Model (handles database operations)
class DatabaseModel {
    public function fetchData() {
        // Database query to fetch data
    }
}

// View (generates HTML output)
class HtmlView {
    public function renderData($data) {
        // Generate HTML output using $data
    }
}

// Controller (intermediary between Model and View)
class DataController {
    private $model;
    private $view;

    public function __construct(DatabaseModel $model, HtmlView $view) {
        $this->model = $model;
        $this->view = $view;
    }

    public function displayData() {
        $data = $this->model->fetchData();
        $this->view->renderData($data);
    }
}

// Implementation
$model = new DatabaseModel();
$view = new HtmlView();
$controller = new DataController($model, $view);
$controller->displayData();