gpt4 book ai didi

php - 难道 PHP 中的 OOD 双重存储 MySQL 中的内容是一种资源浪费吗?

转载 作者:行者123 更新时间:2023-12-01 00:50:21 26 4
gpt4 key购买 nike

<分区>

我的问题是:如果我根据 MySQL 中的数据在 PHP 中创建对象,我是否会双重存储数据并因此浪费资源并减慢我的应用程序?

  1. 人们这样做只是为了将 MySQL 数据缓存为对象以便更快地访问,因为用户不会在每次切换到新产品时都查询数据库吗?
  2. 他们只为不太复杂的代码这样做吗?
  3. 在小型 MVC 中处理此问题的合适方法是什么?即在 session 开始时,模型是否应该创建所有产品的数组?永远不应该有一个包含所有产品的数组,而只是每次询问数据库并将这些数据每次都转换成一个新的 Product 对象吗?

如果你愿意,你可以继续阅读我为什么要问...

我知道这对我的应用程序的大小并不重要,但我想正确地开始它。我有一个我制作的基本的小 MVC 和一个我们称之为产品的项目数据库。为了方便起见,我只是想决定是否/何时/何地从 MySQL 数据到 PHP 对象。

这是我的文件树的样子:

root
controller
Controller.php
model
Model.php
Product.php
view
Products.php
Product.php
index.php

相关代码如下:

// Controller.php
if (!isset($_GET['product'])) {
- getProducts() && include view/Products
} else {
- getProduct('product') && include view/Product
}

// Model.php
getProducts() {
while($row = $stmt->fetch_assoc()) {
$array[$i] = new Product($row["id"], $row["name"], $row["price"]);
$i++;
}
return $array;
}
getProduct($id) {
$allProducts = $this->getProducts();
return $allProducts[$id];
}

// Products view
<?php foreach ($products as $product): ?>
display $product->id and $product->name
<?php endforeach; ?>

// Product view
display $product->name and $product->description and $product->price ...

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com