With the example below, we're taking logs when a property value of an entity is changed. To do this, we use Notify ChangeTracking Policy.


User entity


namespace Application\BackendBundle\Entity;

use Application\BackendBundle\Entity\DomainObject\UserDomainObject;
use Doctrine\ORM\Mapping as ORM;

/**
* @ORM\Entity
* @ORM\Table(name="user")
*/
class User extends UserDomainObject
{
/**
* @var int
*
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;

/**
* @var string
*
* @ORM\Column(name="username", type="string", length=20)
*/
protected $username;

/**
* @var string
*
* @ORM\Column(name="password", type="string", length=40)
*/
protected $password;

/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set username
*
* @param string $username
* @return User
*/
public function setUsername($username)
{
if ($this->username != $username) {
$this->onPropertyChanged('username', $this->username, $username);
$this->username = $username;
}

return $this;
}

/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}

/**
* Set password
*
* @param string $password
* @return User
*/
public function setPassword($password)
{
if ($this->password != $password) {
$this->onPropertyChanged('password', $this->password, $password);
$this->password = $password;
}

return $this;
}

/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
}

UserDomainObject class


namespace Application\BackendBundle\Entity\DomainObject;

use Doctrine\Common\NotifyPropertyChanged;
use Doctrine\Common\PropertyChangedListener;

abstract class UserDomainObject implements NotifyPropertyChanged
{
const LOG_FILE = '../app/logs/listener.log';

private $log = [];
private $listeners = [];

public function addPropertyChangedListener(PropertyChangedListener $listener)
{
$this->listeners[] = $listener;
}

protected function onPropertyChanged($propName, $oldValue, $newValue)
{
if ($this->listeners) {
$content = file_get_contents(self::LOG_FILE);

foreach ($this->listeners as $listener) {
$listener->propertyChanged($this, $propName, $oldValue, $newValue);

$this->log[] = sprintf(
'The value of [%s] has been changed from [%s] to [%s] at [%s].',
$propName,
$oldValue,
$newValue,
date('d/m/Y H:i:s')
);
}

if (! empty($this->log)) {
file_put_contents(self::LOG_FILE, $content . "\n" . implode("\n", $this->log));
$this->log = [];
}
}
}
}

Log file and the result


# app/logs/listener.log

The value of [username] has been changed from [TMRCAL] to [UYBRDA] at [07/07/2015 21:03:13].
The value of [password] has been changed from [1436299385] to [1436299393] at [07/07/2015 21:03:13].
The value of [username] has been changed from [UYBRDA] to [MSUDTG] at [07/07/2015 21:03:18].
The value of [password] has been changed from [1436299393] to [1436299398] at [07/07/2015 21:03:18].