Code The Pixel

CakePHP 4 Audit Trail Using AuditStash Plugin

Asyraf Wahi Anuar - December 04, 2021
Published in CakePHP 1130 Views Email This Article
Estimated reading time: 1 minute, 24 seconds

This plugin adds an "audit trail" to any of your Table classes in your application, allowing the web applications to record the creation, change, or deletion of any table's entities. In theory, it will store the old data before replacing it with the new data or content. The audit log allows the web application to offer systematic tracking of modifications made to specific data. This is extremely beneficial for any online application that requires tracking of content and data.

Repository: https://github.com/lorenzo/audit-stash

Installation
You can install this plugin into your CakePHP application using composer and executing the following lines at the root of your application.

composer require lorenzo/audit-stash


Load the plugin using the following command:

bin/cake plugin load AuditStash


Configuration

In .../config/app.php file add the following configuration:

'AuditStash' => [
    'persister' => 'AuditStash\Persister\TablePersister'
]


Migration

Create Auditstash table using migrations:

bin/cake migrations migrate -p AuditStash -t 20171018185609

Bake the auditlogs table:

bin/cake bake model AuditLogs


Enable Audit Log
Enabling the Audit Log in any of your table classes is as simple as adding a behaviour in the initialize() function:

class ArticlesTable extends Table
{
    public function initialize(array $config = [])
    {
        ...
        $this->addBehavior('AuditStash.AuditLog');
    }
}


Configuring The Behavior
The AuditLog behaviour can be configured to ignore certain fields. By default it ignores the created and modified fields:

class ArticlesTable extends Table
{
    public function initialize(array $config = [])
    {
        ...
        $this->addBehavior('AuditStash.AuditLog', [
            'blacklist' => ['created', 'modified', 'another_field_name']
        ]);
    }
}


You also can define a whitelist. This means that only the fields listed in that array will be tracked by the behaviour:

public function initialize(array $config = [])
{
    ...
    $this->addBehavior('AuditStash.AuditLog', [
        'whitelist' => ['title', 'description', 'author_id']
    ]);
}


That's all. Happy coding :)


Cite this article (APA 6th Edition)