Reputation: 719
Is there a way to use a custom class for a property within a Doctrine entity without creating a relationship?
More specifically, I'm looking to create an entity called TimeClockEvent
that has two properties: $_punchIn
and $_punchOut
. I would like those two properties to be of a type TimeEvent
which only has a basic DateTime
as a value, but has some manipulation methods on it to be able to get the value out in different ways. I would like to be able to map this directly to a datetime
column in the database, rather than having to have a relationship between the two.
Is this possible? I feel like I'm searching for the wrong terms, because the only thing I'm finding is how to create and do various things with custom repositories. I've included some partial examples to further illustrate what I am trying to achieve.
<?php
class TimeEvent{
/** @var $datetime \DateTime **/
protected $_datetime;
public function getUTCDateTime(){
return $this->_datetime;
}
public function getDateTime($timezone)
{
$date = $this->_datetime;
$date->setTimezone(new \DateTimeZone($timezone));
return $date;
}
public function setDateTime(\DateTime $value = null){
if(null === $value){
$this->_datetime = new \DateTime('now', (new \DateTimeZone('UTC')));
return $this;
}
$value->setTimezone(new \DateTimeZone('UTC'));
$this->_datetime = $value;
return $this;
}
}
class TimeClockEvent{
...
/**
* @var $_punchIn TimeEvent
* @ORM\Column(type="datetime")
**/
protected $_punchIn;
/**
* @var $_punchOut TimeEvent
* @ORM\Column(type="datetime")
**/
protected $_punchOut;
...
}
Upvotes: 1
Views: 2001
Reputation: 2745
you can try defining your own custom doctrine mapping type
Just redefining how database types are mapped to all the existing Doctrine types is not at all that useful. You can define your own Doctrine Mapping Types by extending Doctrine\DBAL\Types\Type. You are required to implement 4 different methods to get this working.
1. create mapper class
# AppBundle/Doctrine/Type
<?php
namespace AppBundle\Doctrine\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* My custom datatype.
*/
class TimeEventType extends Type
{
const TIME_EVENT = 'time_event';
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return 'TimeEvent';
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
// work your magic from db value to desirec php value here
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
// work your magic from php value to db value here
}
public function getName()
{
return self::TIME_EVENT;
}
}
2. register new mapping type
# app/config/config.yml
doctrine:
dbal:
types:
time_event: AppBundle\Doctrine\Types\TimeEvent
Upvotes: 3
Reputation: 232
You're looking for a custom Mapping Type
in Doctrine.
You can find the official docs here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html
Upvotes: 0