PHP code example of ez-php / audit

1. Go to this page and download the library: Download ez-php/audit library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ez-php / audit example snippets


// provider/modules.php
return [
    \EzPhp\Audit\AuditServiceProvider::class,
];

use EzPhp\Audit\Event\EntityCreatedEvent;
use EzPhp\Audit\Event\EntityUpdatedEvent;
use EzPhp\Audit\Event\EntityDeletedEvent;
use EzPhp\Events\Event;

// On create:
Event::dispatch(new EntityCreatedEvent(
    entityType: User::class,
    entityId:   $user->id(),
    newValues:  $user->toArray(),
    userId:     $currentUserId,   // optional
));

// On update:
Event::dispatch(new EntityUpdatedEvent(
    entityType: User::class,
    entityId:   $user->id(),
    oldValues:  $previousValues,
    newValues:  $user->toArray(),
    userId:     $currentUserId,
));

// On delete:
Event::dispatch(new EntityDeletedEvent(
    entityType: User::class,
    entityId:   $user->id(),
    oldValues:  $user->toArray(),
    userId:     $currentUserId,
));

use EzPhp\Audit\AuditAction;
use EzPhp\Audit\AuditQuery;

// All audit records for a specific entity:
$records = AuditQuery::for(User::class, $userId)->get();

// Only UPDATE records:
$records = AuditQuery::for(User::class, $userId)
    ->action(AuditAction::UPDATE)
    ->get();

// Records from the last 30 days:
$records = AuditQuery::for(User::class, $userId)
    ->since(new DateTimeImmutable('-30 days'))
    ->get();

// Records up to a date by a specific user:
$records = AuditQuery::for(User::class, $userId)
    ->until(new DateTimeImmutable('2024-12-31'))
    ->byUser($adminId)
    ->get();

// Latest record only:
$latest = AuditQuery::for(User::class, $userId)->first();

// Count:
$count = AuditQuery::for(User::class, $userId)->count();

use EzPhp\Audit\AuditLogger;
use EzPhp\Audit\AuditRecord;
use EzPhp\Audit\AuditAction;

$logger = new AuditLogger($pdo);
$logger->log(new AuditRecord(
    entityType: 'App\\Order',
    entityId:   '123',
    action:     AuditAction::UPDATE,
    oldValues:  ['status' => 'pending'],
    newValues:  ['status' => 'shipped'],
    userId:     'admin',
    createdAt:  new DateTimeImmutable(),
));
bash
composer