Improve this PHP bitfield class for settings/permissions?

后端 未结 5 1439
名媛妹妹
名媛妹妹 2020-12-05 03:48

I have been trying to figure out the best way to use bitmask or bitfields in PHP for a long time now for different areas of my application for different user settings and pe

5条回答
  •  眼角桃花
    2020-12-05 04:13

    "I do like the idea of making it more extensible/generic so different classes can extend this and use it for different sections, i'm just not sure how to do it yet"

    Don't do that, there are various reasons why. In no specific order and just in short: Separate functional classes from data objects. Don't extend what does not need inheritance. Use a property instead, the extending classes normally do not need to be tightly coupled with the bitmask class to work at all. Additionally in PHP you can only extend from one class. If you make use of that for such a limited use, extending objects already have burned that feature.

    So probably you love to not need to do binary calculations in your brain but have a class instead that has encapsulated the binary calculation for you and that offers an interface that is more human (names instead of numbers to say at least) to interact with. Fine. But that's just is it. You can pass along the bitmask by passing the binary value. If you don't need binary values, an enum class instead might be what you're looking for already (check the FlagsEnum in specific).

提交回复
热议问题