|
1 | 1 | # Laravel Bitwise Trait |
2 | | -Simple trait to use bitwise operators on any class |
| 2 | +A simple trait to use bitwise operators on any class |
3 | 3 | Inspired by http://php.net/manual/de/language.operators.bitwise.php#108679 |
4 | 4 |
|
5 | | -I just used it in Laravel so far, but you should be able to use it anyhwere else with minor modifications. |
| 5 | +Updated after reading this blog post: https://aaronfrancis.com/2021/bitmasking-in-laravel-and-mysql |
| 6 | + |
| 7 | +I just used it in Laravel so far, but you should be able to use it anywhere else with minor modifications. |
| 8 | + |
| 9 | +## PHP Version |
| 10 | +Version v2.* requires PHP 8+. If you're stuck to an older version, please use v1.* |
6 | 11 |
|
7 | 12 | ## Installation |
8 | 13 |
|
@@ -34,23 +39,40 @@ There are only a few use-cases for more than one database field, but you can add |
34 | 39 |
|
35 | 40 | Include the Trait in your model like this: |
36 | 41 | ```php |
37 | | -<?php namespace App; |
| 42 | +<?php |
| 43 | + |
| 44 | +namespace App; |
38 | 45 |
|
39 | 46 | use Fanmade\Bitwise\BitwiseFlagTrait; |
40 | 47 |
|
41 | 48 | class Message extends Model |
42 | 49 | { |
43 | | - |
44 | 50 | use BitwiseFlagTrait; |
45 | 51 | ``` |
46 | 52 |
|
47 | 53 | The best way to define your properties is via constants directly in the model. |
48 | | -You're of course free to use config varibales or whatever you prefer. |
| 54 | +You're of course free to use config variables or whatever you prefer. |
49 | 55 | ```php |
50 | | -const MESSAGE_SENT = 1; // BIT #1 of has the value 1 |
| 56 | +const MESSAGE_SENT = 1; // BIT #1 of has the value 1 |
51 | 57 | const MESSAGE_RECEIVED = 2; // BIT #2 of has the value 2 |
52 | | -const MESSAGE_SEEN = 4; // BIT #3 of has the value 4 |
53 | | -const MESSAGE_READ = 8; // BIT #4 of has the value 8 |
| 58 | +const MESSAGE_SEEN = 4; // BIT #3 of has the value 4 |
| 59 | +const MESSAGE_READ = 8; // BIT #4 of has the value 8 |
| 60 | +``` |
| 61 | + |
| 62 | +This alternative syntax may be easier to read: |
| 63 | +```php |
| 64 | +const MESSAGE_SENT = 1 << 0; |
| 65 | +const MESSAGE_RECEIVED = 1 << 1; |
| 66 | +const MESSAGE_SEEN = 1 << 2; |
| 67 | +const MESSAGE_READ = 1 << 3; |
| 68 | +``` |
| 69 | + |
| 70 | +Or directly in binary notation: |
| 71 | +```php |
| 72 | +const MESSAGE_SENT = 0b00000001; |
| 73 | +const MESSAGE_RECEIVED = 0b00000010; |
| 74 | +const MESSAGE_SEEN = 0b00000100; |
| 75 | +const MESSAGE_READ = 0b00001000; |
54 | 76 | ``` |
55 | 77 |
|
56 | 78 | To set a property, just call the function like this: |
|
0 commit comments