2017-09-21 106 views
0

我實際上在PHP中編寫一個類和一個DAO類,如下所示: dbDAO內容只有我的數據庫PDO連接。我想要在我的索引頁上顯示我的數據庫包含的所有產品。從我的數據庫中顯示所有產品的最佳方法是什麼,它是在我的DAO類中還是使用對象產品? DAO類僅用於修改數據庫中的內容?從數據庫顯示數據與類和DAO

這裏是我的代碼:

DAO類:

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 
     } 
    } 

產品類:

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

// GET and SET goes here 

Tancks!

回答

0

永遠不會將HTML(表示邏輯)與業務邏輯相結合。

你可能想要做的是:

定義你的實體(普通PHP對象)定義數據。

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

然後你會讓你的DAO返回你剛定義的實體。

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返回一系列產品。

然後你這個集合傳遞到視圖層,而這正是你可以添加HTML(表示邏輯)

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

我現在看到的! Tancks的幫助! :) – SurveyVisual