我正在制作一个简单的网站,显示存储在数据库中的产品。 有几个类别,每个类别下都有一些产品。 我在考虑为每种产品类型创建一个类,然后将其显示在页面上。
示例数据库表:
product_id | name | category | color | quantity
1 | apple | fruits | green | 10
2 | potat | vegetables | brown | 3
3 | strawberry | fruits | red | 7
现在我只获取水果,我想在网站上显示它们,如果需要,可以选择稍后从页面修改/删除它们。
在这种情况下使用 OOP 有意义吗?
我希望能够使用对象更新信息。或者创造一种新型的产品。例如更改对象的库存数量:
//SQL query to fetch all fruits here
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['quantity'];
}
问题是当我获取所有对象时,我没有将它们存储在一个变量中,所以没有办法声明“$apple=new Fruit()
”例如,所以我不能使用OOP,虽然它在这里使用 OOP 确实是个好主意,这样我就可以实现诸如数量更新方法之类的方法:
$apple->set_quantity(20);
当用户想要更新他拥有的苹果数量时。
这里还有什么方法可以使用OOP吗?
答案 0 :(得分:3)
在使用数据库来管理状态的 (PHP) 应用程序中,通常的做法是将一个对象类映射到您的数据库表中,以便以 OOP 方式与其数据交互。
因此,对于您的表,您将为 product 表实现一个 Product
类,例如:
class Product
{
private int $id;
private string $name;
private string $category;
private string $color;
private int $quantity;
public function __construct(int $id, string $name, string $category, string $color, int $quantity)
{
$this->id = $id;
$this->name = $name;
$this->category = $category;
$this->color = $color;
$this->quantity = $quantity;
}
public function getId(): int
{
return $this->id;
}
public function getName(): string
{
return $this->name;
}
public function getCategory(): string
{
return $this->category;
}
public function getColor(): string
{
return $this->color;
}
public function getQuantity(): int
{
return $this->quantity;
}
public function setQuantity(int $quantity): void
{
$this->quantity = $quantity;
}
}
然后,您通常会使用以下查询来查询 Product
对象:
SELECT * FROM product WHERE category = "fruits"
允许您使用查询结果水合这些 Product
对象:
$products = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$name = $row['name'];
$category = $row['category'];
$color = $row['color'];
$quantity = $row['quantity'];
$products[] = new Product($id, $name, $category, $color, $quantity);
}
生成的 Product
对象从 OOP 的角度“代表”您的数据库数据:
$product->setQuantity(123);
$product->getQuantity(); // 123
但是,您仍然需要实施将持久化 Product
对象返回到您的数据库的方法!