PHP code example of elstc / cakephp-activity-logger

1. Go to this page and download the library: Download elstc/cakephp-activity-logger 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/ */

    

elstc / cakephp-activity-logger example snippets


$this->addPlugin('Elastic/ActivityLogger');

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
            ],
        ]);
    }
}

$article = $this->Articles->newEntity([ /* data */ ]);
$this->Articles->save($article);
// saved log
// [action='create', scope_model='Articles', scope_id=$article->id]

$article = $this->Articles->patchEntity($article, [ /* update data */ ]);
$this->Articles->save($article);
// saved log
// [action='update', scope_model='Articles', scope_id=$article->id]

$article = $this->Articles->get($id);
$this->Articles->delete($article);
// saved log
// [action='delete', scope_model='Articles', scope_id=$article->id]

$this->Articles->setLogIssuer($author); // Set issuer

$article = $this->Articles->newEntity([ /* data */ ]);
$this->Articles->save($article);

// saved log
// [action='create', scope_model='Articles', scope_id=$article->id, ...]
// and
// [action='create', scope_model='Authors', scope_id=$author->id, ...]

// In src/Application.php
use Elastic\ActivityLogger\Http\Middleware\AutoIssuerMiddleware;

class Application extends BaseApplication
{
    public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue
    {
        $middlewareQueue
            // ... other middleware
            ->add(new AuthenticationMiddleware($this))
            
            // Add AutoIssuerMiddleware AFTER authentication middleware
            ->add(new AutoIssuerMiddleware([
                'userModel' => 'Users',           // User model name (default: 'Users')
                'identityAttribute' => 'identity', // Request attribute name (default: 'identity')
            ]))
            
            // ... other middleware
            ->add(new RoutingMiddleware($this));
            
        return $middlewareQueue;
    }
}

// In AppController
class AppController extends Controller
{
    public function initialize(): void
    {
        // ...
        $this->loadComponent('Elastic/ActivityLogger.AutoIssuer', [
            'userModel' => 'Users',  // Specify user model name
        ]);
        // ...
    }
}

class CommentsTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
                'Users',
            ],
        ]);
    }
}

$this->Comments->setLogScope([$user, $article]); // Set scope

$comment = $this->Comments->newEntity([ /* data */ ]);
$this->Comments->save($comment);

// saved log
// [action='create', scope_model='Users', scope_id=$user->id, ...]
// and
// [action='create', scope_model='Articles', scope_id=$article->id, ...]

class ArticlesTable extends Table
{
    public function initialize(array $config): void
    {
        // ...

        $this->addBehavior('Elastic/ActivityLogger.Logger', [
            'scope' => [
                'Articles',
                'Authors',
            ],
        ]);

        // Add message builder
        $this->setLogMessageBuilder(static function (ActivityLog $log, array $context) {
            if ($log->message !== null) {
               return $log->message;
            }
            
            $message = '';
            $object = $context['object'] ?: null;
            $issuer = $context['issuer'] ?: null;
            switch ($log->action) {
                case ActivityLog::ACTION_CREATE:
                    $message = sprintf('%3$s created article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                case ActivityLog::ACTION_UPDATE:
                    $message = sprintf('%3$s updated article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                case ActivityLog::ACTION_DELETE:
                    $message = sprintf('%3$s deleted article #%1$s: "%2$s"', $object->id, $object->title, $issuer->username);
                    break;
                default:
                    break;
            }
            
            return $message;
        });
    }
}

$this->Articles->setLogMessage('Custom Message');
$this->Articles->save($entity);
// saved log
// [action='update', 'message' => 'Custom Message', ...]

$this->Articles->activityLog(\Psr\Log\LogLevel::NOTICE, 'Custom Message', [
  'action' => 'custom',
  'object' => $article,
]);

// saved log
// [action='custom', 'message' => 'Custom Message', scope_model='Articles', scope_id=$article->id, ...]

$logs = $this->Articles->find('activity', ['scope' => $article]);

// Log only when specific fields are changed
if ($article->isDirty('status')) {
    $this->Articles->setLogMessage('Status was changed');
}
$this->Articles->save($article);

// Temporarily disable logging
$behavior = $this->Authors->disableActivityLog();

// Batch processing
foreach ($articles as $article) {
    $this->Articles->save($article);
}

// Re-enable logging
$this->Articles->enableActivityLog();