vendredi 17 juin 2016

Keeping presentation (HTML) and logic (PHP) separate

I am trying to keep presentation and logic separate without using a template engine like Smarty. What I have so far is working, but I am not sure how to do certain things while still keeping things without putting more PHP into my presentation than I would like to. For example, right now I have something like this:

product_list.php

    try {
        $query = $conn->prepare("SELECT p.id, p.name, p.description, IFNULL(url, title) AS url, GROUP_CONCAT(c.category SEPARATOR ', ') AS category,
            FROM products p
            LEFT JOIN product_categories pc ON p.id = pc.product_id
            LEFT JOIN categories c ON pc.category_id = c.id
            WHERE p.active = 1
            GROUP BY p.id");
        $query->execute();
        $result = $query->fetchAll(PDO::FETCH_ASSOC);
    }
    catch (PDOException $e) {
            echo $e->getMessage();
    }
include('templates/product_list_tpl.php');

product_list_tpl.php

<div class="card">
    <div class="product-list with-header">
        <div class="product-list-header center-align">
            <h2><?= $header_title; ?></h2>
        </div>
        <?php foreach ($result as $row): ?>
            <!-- Some Product Info -->
            Category:&nbsp;<?= $row['category']; ?>
        <?php endforeach; ?>
    </div>
</div>

In the above example some products will have one category, some will have multiple. They display nicely in a comma separated list, but I would like to make the category names into links. I know I can do something like below, but it seems messy to me.

<div class="card">
    <div class="product-list with-header">
        <div class="product-list-header center-align">
            <h2><?= $header_title; ?></h2>
        </div>
        <?php 
            foreach ($result as $row):
                $categories = explode(',', $row['category']);
        ?>
                <!-- Some Product Info -->
                Category:&nbsp;
                <?php foreach($categories as $category): ?>
                    <a href="category/<?= strtolower($category); ?>"><?= $category; ?></a>
                <?php endforeach; ?>
        <?php endforeach; ?>
    </div>
</div>

Thank you in advance for any suggestions. Also, if anyone has any input on the general separation format I used on the example code I would love to hear it. I am just getting back into coding after an 8 year break.

EDIT: Added missing endforeach and improved indentation on third code block as per @Devon suggested in comments.

Aucun commentaire:

Enregistrer un commentaire