How can PHP developers separate logic from presentation when generating pagination links to improve code readability and maintainability?
To separate logic from presentation when generating pagination links in PHP, developers can create a separate function or class responsible for generating the pagination links. This helps improve code readability and maintainability by keeping the pagination logic isolated from the presentation layer.
<?php
function generatePaginationLinks($totalPages, $currentPage) {
$links = '';
for ($i = 1; $i <= $totalPages; $i++) {
$activeClass = ($i == $currentPage) ? 'active' : '';
$links .= '<a href="?page=' . $i . '" class="' . $activeClass . '">' . $i . '</a>';
}
return $links;
}
$totalPages = 10;
$currentPage = 5;
echo generatePaginationLinks($totalPages, $currentPage);
?>
Related Questions
- In a PHP application, what steps can be taken to prevent exceeding daily limits for authentication requests and ensure smooth operation of Google Login functionality?
- What potential pitfalls should be considered when automatically creating folders with PHP?
- In what scenarios is it more appropriate to perform timestamp rounding calculations in a database system like MySQL or PostgresSQL instead of in PHP?