PHPackages                             circulon/yii2-flag-behavior - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. circulon/yii2-flag-behavior

ActiveYii2-extension[Utility &amp; Helpers](/categories/utility)

circulon/yii2-flag-behavior
===========================

Bitwise flag setting for Yii 2.x

v1.2.2(10y ago)312.9k3BSD-3-ClausePHP

Since Jun 2Pushed 7y ago1 watchersCompare

[ Source](https://github.com/circulon/yii2-flag-behavior)[ Packagist](https://packagist.org/packages/circulon/yii2-flag-behavior)[ Docs](https://github.com/circulon/yii2-flag-behavior.git)[ RSS](/packages/circulon-yii2-flag-behavior/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (7)Used By (0)

yii2-flag-behavior
==================

[](#yii2-flag-behavior)

Yii 2.x behavior for managing multiple (virtual) boolean attributes stored as a single integer attribute in a model.

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
$ php composer.phar require circulon/yii2-flag-behavior "*"

```

or add

```
"circulon/yii2-flag-behavior": "*"

```

to the `require` section of your `composer.json` file.

Note:
-----

[](#note)

In MySQL (I have not used other DB) we can use TINYINT, SMALLINT, MEDIUMINT, INT &amp; BIGINT which offer 8, 16, 24, 32 &amp; 64 flags respectively. Generally TINYINT(8) or SMALLINT(16) are a good starting point, this also reduces the overhead in your DB.

Usage
-----

[](#usage)

> IMPORTANT: attribute names MUST be unique to the model as per standard attribute naming

> IMPORTANT: The ORDER of attributes (ie the bit position) CANNOT be changed after a record has been inserted. Please check your order before you insert for the first time.

> Additional flags can be added without issue

### Add behavior to the model

[](#add-behavior-to-the-model)

```
    use circulon\flag\FlagBehavior;

    // Recommended to use constants for
    // virtual attribute names
    const SETTINGS_ACTIVE = 'active';
    const SETTINGS_ADMIN = 'admin';
    const SETTINGS_POST_COMMENTS = 'postComments';
    const SETTINGS_VIEW_REPORTS = 'voewReports';
    const SETTINGS_CREATE_REPORTS = 'createReports';

    public function behaviors()
    {
        return [
            'FlagBehavior'=> [
                'class'=> FlagBehavior::className(),
                'fieldattribute' => 'flags', // the db field attribute. Default : 'flags'
                // attributes:  $flag => $position
                //    $flag : the attribute name
                //    $position : the bit position (starting at 0)
                'attributes' => [
                    $this::SETTINGS_ACTIVE => 0,  // The bit position order once set
                    $this::SETTINGS_ADMIN => 1,   // MUST NOT BE CHANGED
                    $this::SETTINGS_POST_COMMENTS => 2, // after any records have been inserted
                ],
                // options: $flag => $options
                //    $flag : the source attribute
                //    $options : an array of $operator => $fields
                //      $operator : (set|clear|not)
                //        set: sets the attribute to a given value (true|false|'source')
                //          'source' will set the attribute to the same as the source ttributes value
                //          if only the attribute name is provided the attribute is set to true
                //
                //        clear: clears the attributes listed
                //        not: sets the value of the attributes to the inverse/complement of the source attribute

                'options' = [
                  $this::SETTINGS_ADMIN => [
                    'set' => [
                      $this::SETTINGS_POST_COMMENTS, // set to true
                      $this::SETTINGS_ACTIVE, // set to true
                    ]
                  ],
                  $this::SETTINGS_ACTIVE => [
                    'set' => [ $this::SETTINGS_POST_COMMENTS => 'source' ], // set same as SETTINGS_ACTIVE
                  ],
                  $this::SETTINGS_CREATE_REPORTS => [
                    'set' => [ $this::SETTINGS_VIEW_REPORTS],
                  ],
                ],
            ],
        ];
    }
```

### Access

[](#access)

> NOTE: it is recommended to use constants for attribute names. Should you decide to change the attribute name (not the position) this will then be used in all models accessing the flags.

```
    // get/set db attribute directly
    $value = $model->fieldAttribute;  // initialy set to 0
    $model->fieldAttribute = 6; // set flags to admin and post comments (110)

    // change flags
    // NOTE:
    //
    $model->{::SETTINGS_ACTIVE} = true; // set flag (now 111)
    $model->active = true;
    $model->setFlag({::SETTINGS_ADMIN}, false); // clear flag (now 101)
    $model->setFlag('postComments', false); // clear flag (now 001)
    $model->{::SETTINGS_ACTIVE} = false; // clear flag (now 000)

    // check if a flag/setting is set
    if ($model->{::SETTINGS_POST_COMMENTS}) {
        // do something here
    }
    if (!$model->active) {
        // show error message
    }
    if ($model->hasFlag({::SETTINGS_ADMIN})) {
        // allow admin user to ....
    }

```

### Searching

[](#searching)

You can simply add criteria for your model/s flags

> NOTE: This may seem a little backwards (ie creating an empty model). but when creating multi model queries this is the simplest method. If you have a better or simpler method, let me know or send a pull request.

Example 1 -- Single model search

```
  //

  $model = new MyModelWithFlags()
  $query = MyModelWithFlags::find();
  // add additional criteria as required
  $query = $model->addFlagsCriteria($query, [
    MyModelWithFlags::SETTING_ACTIVE,  //  Flags with no value are assumed true
    MyModelWithFlags::SETTING_VIEW_REPORTS => false // optionally set the specific (bool or int 1/0) search value
  ]);
  // get records
  $query->all();
  // DataProvider
  $dataProvider = new ActiveDataProvider(['query' => $query]);
```

Example 2 -- Complex (multi-model) search

```
  $searchQuery = PrimarySearchModel::find();
  // add criteria....

  $model = new MyModelWithFlags()
  $searchQuery = $model->addFlagsCriteria($searchQuery, [
    MyModelWithFlags::SETTING_ACTIVE,  //  Flags with no value are assumed true
    MyModelWithFlags::SETTING_VIEW_REPORTS => false // optionally set the specific (bool or int 1/0) search value
  ], true); // generate tablename prefixes

  $otherModel = new MyOtherModelWithFlags()
  // add additional criteria as required
  $searchQuery = $otherModel->addFlagsCriteria($searchQuery, [
    MyOtherModelWithFlags::SETTING_OTHER => true,
    MyOtherModelWithFlags::SETTING_SOME_SETTING => false,
    MyOtherModelWithFlags::SETTING_WORKING,
  ], true); // generate tablename prefixes

  // get records
  $searchQuery->all();
  // DataProvider
  $dataProvider = new ActiveDataProvider(['query' => $searchQuery]);

```

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity29

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~12 days

Total

6

Last Release

3931d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/ed796308e012a4cf7ec03a6386bbd6da40e3a5a776a7a7eef48887e23cdfe67f?d=identicon)[circulon](/maintainers/circulon)

---

Top Contributors

[![circulon](https://avatars.githubusercontent.com/u/499977?v=4)](https://github.com/circulon "circulon (28 commits)")

---

Tags

yii2Behavioryiiflagyii 2bitwisecirculon

### Embed Badge

![Health badge](/badges/circulon-yii2-flag-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/circulon-yii2-flag-behavior/health.svg)](https://phpackages.com/packages/circulon-yii2-flag-behavior)
```

###  Alternatives

[baibaratsky/yii2-serialized-attributes-behavior

Yii2 Serialized Attributes Behavior

1174.1k9](/packages/baibaratsky-yii2-serialized-attributes-behavior)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
