What are some best practices for structuring and organizing PHP code when working with complex data displays like tables?

When working with complex data displays like tables in PHP, it is important to separate your presentation logic from your business logic to keep your code clean and maintainable. One way to achieve this is by using a template engine like Twig to handle the HTML rendering, while keeping your data manipulation and retrieval logic separate in PHP classes or functions.

// Example of using Twig template engine to render a table

// Include Twig autoloader
require_once 'vendor/autoload.php';

// Initialize Twig
$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);

// Data retrieval logic
$data = getDataFromDatabase();

// Render table using Twig template
echo $twig->render('table.twig', ['data' => $data]);