I am not writing "what did I try" or "what is not working" since I can think of many ways to implement something like this. But I cannot believe that no one did something similar before and that is why I would like to ask the question to see what kind of Doctrine2 best practices show up.
What I want is to trigger an event on a property change. So let's say I have an entity with an $active
property and I want a EntityBecameActive
event to fire for each entity when the property changes from false
to true
.
Other libraries often have a PropertyChanged
event but there is no such thing available in Doctrine2.
So I have some entity like this:
<?php
namespace Application\Entity;
class Entity
{
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer");
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var boolean
* @ORM\Column(type="boolean", nullable=false)
*/
protected $active = false;
/**
* Get active.
*
* @return string
*/
public function getActive()
{
return $this->active;
}
/**
* Is active.
*
* @return string
*/
public function isActive()
{
return $this->active;
}
/**
* Set active.
*
* @param bool $active
* @return self
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
}
Maybe ChangeTracking Policy is what you want, maybe it is not!
Check full example in link above.
UPDATE
This is a full example but silly one so you can work on it as you wish. It just demonstrates how you do it, so don't take it too serious!
entity
domainobject
controller
And have this file with 777 permissions (again, this is test) to it:
src/Football/TeamBundle/Entity/log.txt
When you run the code, your log file will have timestamp stored in it, just for demonstration purposes.