How can the separation of concerns be maintained in PHP classes to ensure flexibility in handling data output?
To maintain separation of concerns in PHP classes for flexible data output handling, it's essential to separate the data processing logic from the presentation logic. This can be achieved by creating separate classes or methods for data retrieval and manipulation, and another for rendering the output. By following this approach, changes to the data processing logic won't affect the output rendering, promoting code reusability and maintainability.
<?php
class DataHandler {
public function fetchData() {
// Data retrieval logic
return $data;
}
public function processData($data) {
// Data manipulation logic
return $processedData;
}
}
class OutputRenderer {
public function renderOutput($processedData) {
// Output rendering logic
echo $processedData;
}
}
// Implementation
$dataHandler = new DataHandler();
$outputRenderer = new OutputRenderer();
$data = $dataHandler->fetchData();
$processedData = $dataHandler->processData($data);
$outputRenderer->renderOutput($processedData);
?>