使用 class 和 DAO 显示数据库中的数据

Display data from Database with class and DAO

我实际上在 PHP 一个 class 和一个 DAO class 中编码如下: dbDAO 内容只有我的数据库 PDO 连接。我想在我的索引页面上显示我的数据库包含的所有产品。从我的数据库中显示我的所有产品的最佳方法是什么,是在我的 DAO Class 中还是通过使用对象产品? DAO class 仅用于修改我数据库中的内容?

这是我的代码:

DAO Class :

class ProduitDao extends dbDAO
{
  public function displayProduits()
  {
      $product = $this->bdd->prepare("SELECT * FROM products");
      $product->execute();

      while ($displayProduct = $product->fetch() )
      {
        ?>
        <div class="prodname">
          <?php
          echo '<a href="./product.php?id='.$displayProduct['no'].'"</a>';
          echo '<img src="images/produits/'.$displayProduct['image'].'" alt=" '.$affichageProduit['nom'].' "</img>';
          ?>
        </div>
        <?php
      }
  }

产品 class :

    public function __construct($no, $img)
    {
         $this->no = $numero;
         $this->img = $img;
    }

// GET and SET goes here

坦克!

永远不要将 HTML(表示逻辑)与您的业务逻辑结合起来。

您可能想要做的是:

定义定义数据的实体(普通 PHP 对象)。

class ProductEntity {
     protected id;
     protected name;
     //then define your setters and getters
}

然后您的 DAO 将 return 您刚刚定义的实体。

class ProductDao {
    public function getProducts() {
        $products = [];
        $product = $this->bdd->prepare("SELECT * FROM products");
        $product->execute();

        while ($displayProduct = $product->fetch()) {
             $p = new Product();
             $p->setId($displayProduct['id']);
             $p->setName($displayProduct['name']);
             $products[] = $p;
        }
        return products;
    }
}

现在您可以将您的 DAO 调用到 return 产品集合。

然后您将此集合传递给 VIEW 层,您可以在此处添加 HTML(表示逻辑)

foreach ($products as $product) {
    echo '<div>' . $product->getId() . '</div>';
}