dongzhi6087 2011-04-08 12:42
浏览 30
已采纳

减少php网上商店的数据库调用

I'm looking for a way to prevent repeated calls to the database if the item in question has already been loaded previously. The reason is that we have a lot of different areas that show popular items, latest releases, top rated etc. and sometimes it happens that one item appears in multiple lists on the same page.

I wonder if it's possible to save the object instance in a static array associated with the class and then check if the data is actually in there yet, but then how do I point the new instance to the existing one?

Here's a draft of my idea:

 $baseball = new Item($idOfTheBaseballItem);  
 $baseballAgain = new Item($idOfTheBaseballItem);

 class Item 
 {  
      static $arrItems = array();  

      function __construct($id) {
           if(in_array($id, self::arrItems)){
               // Point this instance to the object in self::arrItems[$id]
               // But how?
          }
          else {
              // Call the database  

              self::arrItems[id] = $this;
          }
      }
 }

If you have any other ideas or you just think I'm totally nuts, let me know.

  • 写回答

2条回答 默认 最新

  • duanpanhuo0618 2011-04-08 12:47
    关注

    You should know that static variables only exist in the page they were created, meaning 2 users that load the same page and get served the same script still exist as 2 different memory spaces.

    You should consider caching results, take a look at code igniter database caching

    What you are trying to achieve is similar to a singleton factory

    $baseball = getItem($idOfTheBaseballItem);  
    $baseballAgain =getItem($idOfTheBaseballItem);
    
    function getItem($id){
        static $items=array();
        if(!isset($items[$id])$items[$id]=new Item($id);
        return $items[$id];
    }
    
    class Item{  
        // this stays the same
    }
    

    P.S. Also take a look at memcache. A very simple way to remove database load is to create a /cache/ directory and save database results there for a few minutes or until you deem the data old (this can be done in a number of ways, but most approaches are time based)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大