PHPackages                             antonyz89/change-log-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. antonyz89/change-log-behavior

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

antonyz89/change-log-behavior
=============================

Simple changelog behavior for yii2 models

1.2.4(1y ago)01.2k↓100%MITPHP

Since Jul 18Pushed 1y agoCompare

[ Source](https://github.com/AntonyZ89/change-log-behavior)[ Packagist](https://packagist.org/packages/antonyz89/change-log-behavior)[ RSS](/packages/antonyz89-change-log-behavior/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (1)Versions (28)Used By (0)

Changelog Behavior simplified(v.1.0.0)
======================================

[](#changelog-behavior-simplifiedv100)

Simple behavior for your yii2-models

**forked from [Cranky4/change-log-behavior](https://github.com/Cranky4/change-log-behavior)**

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

[](#installation)

1- Install package via composer:

```
composer require antonyz89/change-log-behavior "*"

```

2- Run migrations:

```
yii migrate --migrationPath=@vendor/antonyz89/change-log-behavior/src/migrations

```

Usage
-----

[](#usage)

1- Add *ChangeLogBehavior* to any model or active record:

```
public function behaviors()
{
    return [
        ...
        [
            'class' => ChangeLogBehavior::className(),
            'db' => Yii::$app->other_db, # optional (default is the same as Yii::$app->db)
            'excludedAttributes' => ['updated_at'],
        ],
        ...
    ];
}
```

**Attention:** Behavior watches to "safe" attributes only. Add attributes into *excludedAttributes* if you don't want to log its changes.

2- Add *ChangeLogList* to view:

```
 echo ChangeLogList::widget([
     'model' => $model,
 ])
```

3- Add custom log:

```
$model->addCustomLog('hello world!', 'hello_type')
```

### Custom fields

[](#custom-fields)

With custom fields, you can store additional values in a property called `custom_fields`. This feature is useful when you need to save values generated based on other fields or relations.

```
public function behaviors()
{
    return [
        [
            'class' => ChangeLogBehavior::class,
            'autoCache' => true,
            'customFields' => [
                'total' => static function (self $model) {
                    return $model->calculateTotal();
                },
                // or static function (self $model) { return $model->createdBy->name; }
                'created_by' => 'createdBy.name'
            ]
        ]
    ];
}
```

Use `!` after the field's name to force it to be saved even if it hasn't changed.

```
public function behaviors()
{
    return [
        [
            'class' => ChangeLogBehavior::class,
            'autoCache' => true,
            'customFields' => [
                'total' => static function (self $model) {
                    return $model->calculateTotal();
                },
                // `user_id` will be registered even if it hasn't changed
                'user_id!' => 'user.name',
                'created_by' => 'createdBy.name'
            ]
        ]
    ];
}
```

How it works:

- When finding a model, the custom field is activated to cache the current values of custom fields. Upon saving the model, the custom fields are regenerated to store both the before and after values.

    ```
    {
        "title": ["Hello World", "New Title"],
        "custom_fields": {
            "total": [50, 100]
        }
    }
    ```
- Auto cache custom fields

    - By default `$autoCache` is `false` and the custom fields are not cached on trigger `ActiveRecord::EVENT_AFTER_FIND` to prevent performance issues.
    - Call `cacheCustomFields()` to cache the custom fields manually. ```
        class FooController extends Controller {
            // ...

            public function actionUpdate($id) {
                $model = $this->findModel($id);
                // cache custom fields manually
                // [[cacheCustomFields()]] is a magic method that calls [[ChangeLogBehavior::cacheCustomFields()]]
                $model->cacheCustomFields();

                $modelChildren = array_map(function () {
                    // imagine something cool here
                }, $this->request->post());

                foreach ($modelChildren as $modelChild) {
                    $modelChild->parent_id = $model->id;
                    $modelChild->save();
                }

                // on save the custom fields are computed again and saved if they changed
                $model->save();
            }
        }
        ```
    - To enable `$autoCache` set it to `true` on behaviors and the custom fields will be cached on trigger `ActiveRecord::EVENT_AFTER_FIND`. But be careful.

### Save data on delete

[](#save-data-on-delete)

By default the behavior doesn't save data on delete. Set `dataOnDelete` to `true` to save data on delete.

```
/**
 *  @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ChangeLogBehavior::class,
            'dataOnDelete' => true
        ]
    ];
}
```

The result will be something like:

```
{
    "field_1": ["value", null],
    "field_2": ["value", null],
    "field_3": ["value", null],
}
```

Last value is always `null`.

`dataOndelete = true` also save custom fields.

Parent Id
---------

[](#parent-id)

Set a parent id to change log.

This is useful to create a custom view for your changelog view.

default: `null`, accept: `null` | `string` | `callable`

```
public function behaviors()
{
    return [
        [
            'class' => ChangeLogBehavior::class,
            // get `user_id` from model ($model->user_id)
            'parentId' => 'user_id',
            // get `user_id` from model using static function
            'parentId' => static functiobn (self $model) {
                if ($model->type !== 'ADMIN')
                    return $model->user_id;
                }

                return null;
        ]
    ];
}
```

Example
-------

[](#example)

Model *Post*

```
/**
 * @propertu int id
 * @property int created_at
 * @property int updated_at
 * @property string title
 * @property int rating
 */
class Post extends yii\db\ActiveRecord {

    /**
     *  @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
                'class' => ChangeLogBehavior::class,
                'excludedAttributes' => ['created_at','updated_at'],
                // (optional) autoCache is disabled by default
                'autoCache' => false,
                // (optional) - custom fields
                'customFields' => [
                    'total' => static function (self $model) {
                        return $model->calculateTotal();
                    },
                    // or static function (self $model) { return $model->createdBy->name; }
                    'created_by' => 'createdBy.name'
                ]
            ]
        ];
    }
}
```

View *post/view.php*

```
use antonyz89\ChangeLogBehavior\ListWidget as ChangeLogList;
use app\models\Post;

/**
 *  @var Post $model
 */
echo DetailView::widget([
    'model' => $model,
    'attributes' => [
        'id',
        'title',
        'rating',
        'created_at:datetime',
        'updated_at:datetime',
    ],
]);

echo ChangeLogList::widget([
    'db' => Yii::$app->other_db, # optional (default is the same as Yii::$app->db)
    'model' => $model,
]);
```

###  Health Score

36

—

LowBetter than 81% of packages

Maintenance33

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity73

Established project with proven stability

 Bus Factor1

Top contributor holds 71.4% 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 ~110 days

Recently: every ~48 days

Total

27

Last Release

711d ago

Major Versions

0.1.4 → 1.0.02018-07-11

### Community

Maintainers

![](https://www.gravatar.com/avatar/68c187c364cc778fd93b1ca011536893e6fc1e9e9c1b0dfee490fb23904265ae?d=identicon)[AntonyDev](/maintainers/AntonyDev)

---

Top Contributors

[![Cranky4](https://avatars.githubusercontent.com/u/5602347?v=4)](https://github.com/Cranky4 "Cranky4 (40 commits)")[![AntonyZ89](https://avatars.githubusercontent.com/u/1340674?v=4)](https://github.com/AntonyZ89 "AntonyZ89 (14 commits)")[![avbondarev](https://avatars.githubusercontent.com/u/491595?v=4)](https://github.com/avbondarev "avbondarev (1 commits)")[![seisvalt](https://avatars.githubusercontent.com/u/295823?v=4)](https://github.com/seisvalt "seisvalt (1 commits)")

---

Tags

yii2changelog

### Embed Badge

![Health badge](/badges/antonyz89-change-log-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/antonyz89-change-log-behavior/health.svg)](https://phpackages.com/packages/antonyz89-change-log-behavior)
```

###  Alternatives

[cranky4/change-log-behavior

Simple changelog behavior for yii2 models

1626.3k](/packages/cranky4-change-log-behavior)[dmstr/yii2-cookie-consent

Yii2 Cookie Consent Widget

1452.6k](/packages/dmstr-yii2-cookie-consent)[richardfan1126/yii2-js-register

Yii2 widget to register JS into view

1357.2k7](/packages/richardfan1126-yii2-js-register)

PHPackages © 2026

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