dongshuzui0335 2018-02-02 10:04
浏览 76
已采纳

PHP对象通过类静态属性进行缓存

This is a question about general performance through implementing the solution shown below. I am aware that this might be slightly opinion based, but I want to know if anyone has a clear idea as to if this is a good implementation, or if it should be solved in a better way.

This is just an example, but lets first create a class called Member. This will be instantiated multiple times when we are listing all Members in the database. Now, since in this example, this is an old and complicated system, every time the full list of members is shown, one member can be instantiated multiple times. So to reduce the entire operation of fetching the member every time, we cache the instantiated object in a static property of the class, and returns that if it already exists:

class Member {

    protected static $cachedMember = null;

    public static function get($id){
        if ( isset( self::$cachedMember[$id] ) ) return self::$cachedMember[$id];
        // If its not set, we fetch it from database...
        $obj = new static();    
        // Fetching member from database and applying the applicable values to $obj 
        // Then we set the filled $obj to the $cachedMember static. 
        self::$cachedMember[$id] = $obj;
        return $obj;
    }

}

Obviously, this will take up some memory, depending on how many times the Member class is instantiated with a unique member id. But this is released in turn when the script have ended (correct?). So as long as PHP has enough memory allocated, it's to my understanding no other downside to this implementation?

  • 写回答

1条回答 默认 最新

  • dpymrcl269187540 2018-02-02 10:19
    关注

    Yes, that approach should work to avoid fetching a member with the same ID more than once from your database during the runtime of your script.

    Yes, the memory is released when the script ends, but memory should not be a big issue here, since PHP is only storing a reference to each object in your static array, not the object itself.

    One typo:
    $obj = new self();

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵