php memcache orm缓存和清除


php memcache orm caching and purging

我想为我的ORM实现一个基于memcache的缓存。让我们假设,我在用户模型上有两个方法来获取相同的数据集:

 + findById(1234);
 + findByUsername('roman');

不同的查询,相同的结果集。现在,这两个结果集都由memcache缓存在不同的键下(包含用于分隔它们的mysqlwhere语句)。在编辑用户模型后进行清除时非常糟糕。我必须清除2个我不知道的密钥,因为密钥看起来像这样:

+ findById       -> user_id_1234_visible_true_enabled_true (and so on)
+ findByUsername -> user_username_roman_visible_true_enabled_true (and so on)

现在的问题是,如何清除这两个密钥。

到目前为止,我找到的唯一解决方案是将findByUsername拆分为两个mysql调用:

1. findIdByUsername()
2. get id from resultset
3. findById(withFetchedId)
4. cache findById resultset

我希望你能给我一个提示,让我想出另一个解决方案。太多了!

有一种方法可以覆盖特定模型上的Model::find()Model::findFirst(),方法如ORM缓存手册中所述。但我认为它不能100%解决你的问题,除非:

a)根据数据库中的用户数量,我可能会缓存{login: id}的完整集合-中小型CRM案例

b)或在需要它们时缓存一段时间:

1. if userId not in cache, fetch from findIdByUsername() and cache it under username
2. get userId from cache based on username
3. findById()

因此,在现实中,您会不时询问userId,它具有基于getUserById()的核心功能,这是一种非常合适的方法。