2011-08-20 74 views
0

我想在我的ORM中做一些缓存为每个孩子分隔静态变量

class Base { 

    static public $v=array(); 
    static public function createById($id){ 
     if(!array_key_exists($id, static::$v)){ 
      static::$v[$id] = new static; //Get from DB here. new static is just example 
     } 
     return static::$v[$id]; 
    } 

} 

class User extends Base{ 

} 
class Entity extends Base{ 

} 

但现在缓存合并

var_dump(User::createById(1)); 
var_dump(Entity::createById(1)); 

结果

object(Model\User)#4 (0) { 
} 
object(model\User)#4 (0) { 
} 

如果我制作了

class Entity extends Base{ 
    static public $v=array(); 
} 
class User extends Base{ 
    static public $v=array(); 
} 

我得到了什么我需要:

object(Model\User)#4 (0) { 
} 
object(model\Entity)#5 (0) { 
} 

是否有可能在每个课程中都没有声明?

回答

1

如果重要的是您不重新声明每个子类中的属性,我唯一能想到的解决方案就是,这不完全是您想要的,但它应该为您提供相同的功能,在共享同一财产上的基类来存储缓存所有的子类,但是使用子类的名称作为高速缓存阵列中的一个关键:

class Base { 
    public static $v=array(); 
    public static function createById($id){ 
     $called = get_called_class(); 
     if (!isset(self::$v[$called])) { 
      self::$v[$called] = array(); 
     } 
     $class_cache = &self::$v[$called]; 
     if(!array_key_exists($id, $class_cache)){ 
      $class_cache[$id] = new static; 
     } 
     return $class_cache[$id]; 
    } 
} 

是的,它不漂亮......但据我所知,你所要求的是不可能的。

+0

无论如何,它比每个孩子班级的重新宣言都更加美丽:) 1曾经写过,没有多想过,谢谢。 – RiaD