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?

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

这是一个关于通过实施下面所示解决方案的一般性能的问题。 我知道这可能是基于意见的,但我想知道是否有人清楚地知道这是一个好的实现,还是应该以更好的方式解决。

这只是一个例子,但我们先创建一个名为Member的类。 当我们列出数据库中的所有成员时,这将被多次实例化。 现在,因为在这个例子中,这是一个古老而复杂的系统,每次显示完整的成员列表时,可以多次实例化一个成员。 因此,为了减少每次获取成员的整个操作,我们将实例化对象缓存在类的静态属性中,如果它已经存在则返回:

  class Member  {
 
 protected static $ cachedMember = null; 
 
公共静态函数get($ id){
 if(isset(self :: $ cachedMember [$ id]))return self :: $ cachedMember [$  id]; 
 //如果没有设置,我们从数据库中获取它... 
 $ obj = new static();  
 //从数据库中获取成员并将适用的值应用于$ obj 
 //然后我们将填充的$ obj设置为$ cachedMember static。  
 self :: $ cachedMember [$ id] = $ obj; 
返回$ obj; 
} 
 
} 
   
 
 

显然,这将是 占用一些内存,具体取决于使用唯一成员标识实例化 Member 类的次数。 但是当脚本结束时(这是正确的?)依次释放。 所以只要PHP有足够的内存分配,我的理解是没有其他的缺点这个实现?

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

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();

    点赞 评论

相关推荐 更多相似问题