简体   繁体   English

PHP:用数学管理角色?

[英]PHP: Manage roles with math?

I once saw an article about how to use a specific type of numbering system to manage roles. 我曾经看过一篇关于如何使用特定类型的编号系统来管理角色的文章。 A user would be assigned a specific role number and depending on a calculation, the number could stand for multiple roles. 将为用户分配特定的角色编号,并且根据计算,该编号可以代表多个角色。

Can anybody share this technique with me or share a link? 任何人都可以与我分享这项技术或分享链接吗? Thanks! 谢谢!

It is a bitmask. 这是一个位掩码。 It works like this: you assign to each role a progressive number, then when you want to assign one role to a user, you pick the number of that role. 它的工作方式如下:您为每个角色分配一个渐进式数字,然后当您想要为用户分配一个角色时,您可以选择该角色的编号。 If you want to add another role, you just add that role number to the original one. 如果要添加其他角色,只需将该角色编号添加到原始角色即可。 You can add as many roles as you wish. 您可以根据需要添加任意数量的角色。 The trick is just how you choose your numbers: they are the powers of 2. 诀窍在于你如何选择数字:它们是2的幂。

Here is an example: 这是一个例子:

Role: Editor.     Value: 2^0 = 1
Role: Manager.    Value: 2^1 = 2
Role: Supervisor. Value: 2^2 = 4
Role: Admin.      Value: 2^3 = 8
...

To give a user the role of Editor, you save 1 to the database, To give a user the roles of Editor, Manager and Admin you save 1 + 2 + 8 = 11 要为用户提供编辑器的角色,请将1保存到数据库中。要为用户提供编辑器,管理员和管理员的角色,请保存1 + 2 + 8 = 11

You can see why this works, if you see it as an array of 1 or 0 values. 如果您将其视为1或0值的数组,您可以看到它的工作原理。

|__|__|__|__|__|__|
    16  8  4  2  1

Each role is a 1 in the corresponding slot. 每个角色在相应的插槽中为1。 So our 11 case is: 所以我们的11个案例是:

|__|__|_1|_0|_1|_1|
    16  8  4  2  1

If you have a bitmask, and you want to know whether the user has a certain role, you use this operation: 如果您有位掩码,并且想要知道用户是否具有某个角色,则使用此操作:

(bitmask & role_value) >= 1 (bitmask&role_value)> = 1

For example: 例如:

(11 & 8) >= 1? (11和8)> = 1? yes, so the user has the admin role 是的,所以用户具有管理员角色
(11 & 4) >= 1? (11&4)> = 1? no, so the user has not the supervisor role 不,所以用户没有主管角色

It is called a bitmask, because what you are doing is to "check whether in a particular position there is a 1", that is, "apply a mask which will mask (set to 0) all the places, except the one you are searching for): 它被称为位掩码,因为你正在做的是“检查特定位置是否有1”,即“应用一个掩码(设置为0)所有位置,除了你是寻找):

11 --> |__|__|_1|_0|_1|_1|
           16  8  4  2  1 
 8 --> |__|__|_1|_0|_0|_0|  (mask)
           16  8  4  2  1 
AND -> |__|__|_1|_0|_0|_0|  Result: Yes

Hope it helped :) 希望它有帮助:)

i think you have heard of "bit-flags". 我想你听说过“比特旗”。 i don't know a good english turorial for that (i'm german) - but i think google will give you some nice links. 我不知道这是一个很好的英语版(我是德国人) - 但我认为谷歌会给你一些不错的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM