The Mahana Bitfield Library for Settings Sanity

Tag: PHP v5.0+

Driven crazy with all the flags being constantly added to your tables? Migrations files stacked higher than the *other* Jeff Madsen's poker chips at a championship game? Have no fear!

The Mahana Bitfield Library is a simple and useful library. Using Bitfield Masking we can condense up to 31 separate flags to a single integer setting in much the same way that Unix permission are used.

The READ.ME explains the setup, but in short, you 1) created a new class that inherits from MahanaBitfield abstract class, 2) set up the flags you want in your new class, 3) there is no three - you just use it now.

So given a set of flags such as:

public $flags = [
    'flag1' => 0,
    'flag2' => 1,
    'flag3' => 2,
];

You can set each one to true or false. The bitmasking calculates a unique value for that particular arrangement. Each flag's `value` is double the preceding one, and all the "true" settings are added up.

$settings = [
    'flag1' => true,
    'flag2' => false,
    'flag3' => true,
];

// 1 + 0 + 4 = 5

$settings = [
    'flag1' => false,
    'flag2' => true,
    'flag3' => true,
];

// 0 + 2 + 4 = 6

Those values are not anything you even have to worry about - it is all calculated internally. If you need to get or set a particular flag, use:

$user_settings->flag1 = true;

// or

$flag1 = $user_settings->flag1

The array methods `getFlags` and `setFlags` were made to allow you to easily pass values back and forth from your forms.

Special thanks to Dan Cowell whose suggestions greatly improved the usability.

Hope that helps!

Read it Monday, Use it by Friday!

Laravel Quick Tips Weekly Newsletter. Short, immediately helpful bits you'll use in your own codebase before the next one arrives.

Join us now and get a FREE PDF of the first fix months of Laravel Quick Tips!

No Spam, Unsubscribe Anytime

Contact me