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

通过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?

图片转代码服务由CSDN问答提供 功能建议

我有许多扩展抽象DatabaseRecord类的类。 实质上,DatabaseRecord类处理所有子类在与数据库交互时使用的一些常用函数(例如,通过id,更新等进行搜索)。

现在,我想要 每次都不必经常去DB获取记录,例如,在页面加载时引用特定用户。 我有一个中等巧妙的想法,因此我可以执行以下操作,因为PHP具有后期静态绑定。

 抽象类DatabaseRecord {
 static protected $ cachedRecords; 
 \  n public static function searchById($ id){
 if(!isset(static :: $ cachedRecords [$ id])){
 // logic 
 static :: $ cachedRecords [$ id] = static :: constructFromDatabase  ($ results); 
} 
返回static :: $ cachedRecords [$ id]; 
} 
 // ...更多逻辑
} 
   
 
  

不幸的是,所有子类共享相同的静态 $ cachedRecords

我可以通过在所有子类中重新声明 static protected $ cachedRecords; 并在DatabaseRecord中声明 $ cachedRecords 来解决这个问题。 private 阻止我忘记重新声明,但这似乎是一个不优雅的解决方案。

有没有更好的方法来做到这一点,所以它是一次写入和 - 忘了?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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;
        }
    }
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题