Reputation: 3678
In a Symfony2 project, I am using a custom Doctrine type 'unixtime' to map date fields stored as unix timestamps in a legacy database:
/**
* @var \DateTime
* @ORM\Column(name="created", type="unixtime", nullable=false)
*/
private $created;
Now I'd like to use DoctrineExtensions and stof/doctrine-extensions-bundle
to set this property automatically by adding:
* @Gedmo\Timestampable(on="create")
But this results in an exception, because "unixtime" is not among the $validTypes
in Gedmo\Timestampable\Mapping\Driver\Annotation
:
Field - [created] type is not valid and must be 'date', 'datetime' or 'time' in class ...
When I add 'unixtime' directly to that array of valid types, everything works fine.
What would be the best and least intrusive way to make the Timestampable handler work with my custom type? Is there a way to configure this? Do I need to subclass?
Upvotes: 1
Views: 1312
Reputation: 3678
After some extensive research, I've come up with a solution that works for me. Not quite as elegant as I would have hoped, but I'd like to share anyway.
First, I registered my own TimestampableListener
:
stof_doctrine_extensions:
class:
timestampable: MyProject\TimestampableListener
... to override getNamespace()
:
namespace MyProject;
class TimestampableListener extends \Gedmo\Timestampable\TimestampableListener
{
protected function getNamespace()
{
return __NAMESPACE__;
}
}
This will cause DoctrineExtensions to load the annotation mapping driver from my namespace as well, so I can extend it and add my custom type to the list of allowed types:
namespace MyProject\Mapping\Driver;
class Annotation extends \Gedmo\Timestampable\Mapping\Driver\Annotation
{
protected $validTypes = array(
'date', 'time', 'datetime', 'datetimetz', 'timestamp',
'zenddate', 'vardatetime', 'integer',
// our custom field type:
'unixtime',
);
}
Unfortunately, it will also cause the corresponding field adapter to be loaded from my namespace. So I have to add that one, too. And since the original adapter class is declared final
, I'm basically forced to copy the implementation:
namespace MyProject\Mapping\Event\Adapter;
final class ORM extends BaseAdapterORM implements TimestampableAdapter
{
public function getDateValue($meta, $field)
{
// code from Gedmo\Timestampable\Mapping\Event\Adapter::getDateValue()
...
}
}
Upvotes: 2