我想要做的是編寫一個「搜索」類,它可以搜索產品列表並將它們存儲在一個數組中。類從另一個類創建對象,但具有較少的開銷
我已經有一個「產品」類,可用於獲取特定產品的詳細信息。
這裏是我的代碼:
class Product {
public $name;
public $price;
public $description;
public function getProductById ($id) {
$sql = 'SELECT name, price, description FROM product WHERE id = ' . $id;
$row = /* MySQL functions here to execute SQL statement and get a matching row */
$this->name = $row['name'];
$this->price = $row['price'];
$this->description = $row['description'];
return TRUE;
}
}
class Search {
public $results;
public $totalResults;
function __construct() {
$this->results = array();
$this->totalResults = 0;
}
public function doSearch ($name) {
$sql = 'SELECT id FROM product WHERE name LIKE "%' . $name . '%"';
$rows = /* MySQL functions here to execute SQL statement and get a list of matching product ID's */
foreach ($rows as $row) {
$product = new Product;
$product->getProductById ($row['productid']);
$this->results[] = $product;
}
return TRUE;
}
}
$search = new Search;
$search->doSearch ('Fresh Flowers');
的問題與上面的是,在doSearch方法所有匹配的記錄將在getProductById方法執行查詢。如果有100個匹配的產品,則會在產品類中執行100個單獨的查詢。
但是,如果我使用單個查詢直接在doSearch方法中獲取產品,則會完全繞過Product類。
當一個「產品」是一個對象時,編寫一個可以返回「產品」對象列表的搜索類的最合適的方式是什麼,而不需要我在上面做什麼的開銷?
上什麼'join'在SQL讀了。 – goat
@rambocoder JOIN在這裏幾乎沒有用處。 – phant0m
哦,我沒有注意到兩個查詢中都使用了同一張表。 – goat