doufang2228 2013-09-27 08:28
浏览 95
已采纳

通过PHP中的静态属性进行缓存

I have a number of classes that extend an abstract DatabaseRecord class. Essentially, the DatabaseRecord class handles some common functions that all of the child classes use in interacting with the database (e.g. searching by id, updating, etc.).

Now, I'd like to not have to constantly go to the DB to fetch the record every time, for example, a particular user is referenced on a page load. I had a moderately ingenious idea, such that I could do the following, since PHP has late static binding.

abstract class DatabaseRecord{
    static protected $cachedRecords;

    public static function searchById($id){
        if(!isset(static::$cachedRecords[$id])) {
              // logic
              static::$cachedRecords[$id] = static::constructFromDatabase($results);
        }
        return static::$cachedRecords[$id];
    }
    // ... more logic
}

Unfortunately, all the child classes share the same static $cachedRecords.

I could fix this by redeclaring static protected $cachedRecords; in all the child classes and declaring the $cachedRecords in DatabaseRecord to be private to stop me from forgetting the redeclaration, but this seems an inelegant solution.

Is there a better way of doing this so it's write-once-and-forget?

  • 写回答

1条回答 默认 最新

  • dongzhi4498 2013-09-27 08:36
    关注

    You could just add another level to the $cachedRecords array that indicates the actual class:

    static public function cache( $id )
    {
        $class = get_called_class();
    
        if( isset( self::$cachedRecords[$class][$id] ) )
        {
            return self::$cachedRecords[$class][$id];
        }
        else
        {
            return null;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何解决y_true和y_predict数据类型不匹配的问题(相关搜索:机器学习)
  • ¥15 PB中矩阵文本型数据的总计问题。
  • ¥40 宿舍管理系统设计(c#)
  • ¥15 MATLAB卫星二体模型仿真
  • ¥15 怎么让数码管亮的同时让led执行流水灯代码
  • ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
  • ¥85 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。