通过PHP和MySQL检查用户的声誉 [英] Checking user's reputation by PHP vs MySQL

查看:103
本文介绍了通过PHP和MySQL检查用户的声誉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问答网站(类似SO)。我想实现此条件:

I have a question-and-answer website (something like SO). I want to implement this condition:


条件:用户可以给予投票权

我可以通过两种方式实现该条件:

Well I can implement that condition in two ways:

服务器端:当用户登录时,我得到他的声誉,并将其设置为 $ _ SESSION ['rep']

Server Side: When user log in, I get his reputation and set it into $_SESSION['rep']. Then use it before commenting

if( $_SESSION['rep'] >= 125 ) { /* can vote */ } else { /* cannot vote */ }

边:我可以使用触发器,并检查如下:

Database Side: I can use a trigger and check it like this:

IF ( SELECT 1 FROM user WHERE id = new.user_id AND rep < 125) THEN
    SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = "cannot vote";
END if;`






测试他们和他们工作,以及。现在我想知道哪一个更常见和标准?


I have tested both of them and they work as well. Now I want to know which one is more common and standard?

推荐答案

时间(不是通过使用触发器,而是通过在注释之前查询数据库并在PHP中检查用户的信誉)。

Personally, I've been using the Database Side approach all the time (not by using a trigger but by querying the database before commenting and checking user's reputation in PHP). It will not slow down the performance too much.

但是,如果你真的需要性能好,你可以在内存中缓存用户信誉(不要使用$ _SESSION,它很容易导致不一致问题)。如何使用Redis / Memcached?当用户登录时,将他/她的信誉放在缓存中。当用户的信誉在数据库中更新时,更新(无效)缓存。当你需要弄清楚用户是否具有向下投票的权限,你只需要咨询你的缓存,没有db查询涉及。

However, if you really need the performance to be good, you may cache user reputation in memory (don't use $_SESSION, it will easily lead to inconsistency problems). What about using Redis/Memcached? When the user logs in, put his/her reputation in the cache. When the user's reputation is updated in the database, update(invalidate) the cache too. When you need to figure out whether the user has the permission to down vote, you just need to consult your cache, no db query involved.

缓存的键应该类似于 user_rep_5 (其中5是user_id),而不是 user_rep_xxxx (其中xxxx是会话ID)。我的意思是,缓存应该做全局,以确保只有一个单一的真相来源,而不是将其与会话相关联。

P.S. They key of the cache should look like user_rep_5 (where 5 is the user_id), not user_rep_xxxx (where xxxx is the session id). I mean, the cache should be done globally to make sure there is only one single source of truth, instead of associating it with the session.

这篇关于通过PHP和MySQL检查用户的声誉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆