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',
],
]);
}
}
$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, ...]
// Log only when specific fields are changed
if ($article->isDirty('status')) {
$this->Articles->setLogMessage('Status was changed');
}
$this->Articles->save($article);