PHP code example of bentools / doctrine-watcher

1. Go to this page and download the library: Download bentools/doctrine-watcher 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/ */

    

bentools / doctrine-watcher example snippets


use App\Entity\User;
use BenTools\DoctrineWatcher\Changeset\PropertyChangeset;
use BenTools\DoctrineWatcher\Watcher\DoctrineWatcher;

/**
 * Instanciate watcher
 */
$watcher = new DoctrineWatcher();

/**
 * Register it as an event subscriber
 * @var \Doctrine\Common\EventManager $eventManager
 */
$eventManager->addEventSubscriber($watcher);

/**
 * Watch for changes on the $email property for the User class
 */
$watcher->watch(User::class, 'email', function (
    PropertyChangeset $changeset,
    string $operationType,
    User $user
) {

    if (!$changeset->hasChanges()) {
        return;
    }

    vprintf('Changed email from %s to %s for user %s' . PHP_EOL, [
        $changeset->getOldValue(),
        $changeset->getNewValue(),
        $user->getName(),
    ]);
});

/**
 * Watch for changes on the $roles property for the User class
 */
$watcher->watch(User::class, 'roles', function (
    PropertyChangeset $changeset, 
    string $operationType, 
    User $user
) {

    if ($changeset::INSERT === $operationType) {
        return;
    }

    if ($changeset->hasAdditions()) {
        vprintf('Roles %s were granted for user %s' . PHP_EOL, [
            implode(', ', $changeset->getAdditions()),
            $user->getName(),
        ]);
    }

    if ($changeset->hasRemovals()) {
        vprintf('Roles %s were revoked for user %s' . PHP_EOL, [
            implode(', ', $changeset->getRemovals()),
            $user->getName(),
        ]);
    }
});

$watcher = new DoctrineWatcher(['trigger_on_persist' => true]); // Will be default config for all watchers

$watcher->watch(Entity::class, 'property', $callable, ['trigger_on_persist' => true]); // Will apply on this watcher only

$watcher = new DoctrineWatcher(['trigger_when_no_changes' => true]); // Will be default config

$watcher->watch(Entity::class, 'property', $callable, ['trigger_when_no_changes' => true]); // Will apply on this watcher only