A price object has three properties,
/** @var float */
public $amount = 0.0;
/** @var string */
public $currency = '';
/**
* @var \DateTime
*/
public $dueDate;
When serializing this object to json via the symfony2 Symfony\Component\HttpFoundation\JsonResponse, it will look like:
{
"price": {
"amount": 235,
"currency": "EUR",
"dueDate": {
"date": "2015-10-25 00:00:00.000000",
"timezone": "UTC",
"timezone_type": 3
}
}
}
I want the \DateTime to be formatted as simply a string:
"dueDate": "2015-10-22 00:00:00.000000"
How to get this done is not the scope of the question, as I currently handle this case in the object's constructor:
/**
* Price constructor.
* @param float $amount
* @param string $currency
* @param \DateTime|null $dueDate
*/
public function __construct($amount = 0.0, $currency = "", $dueDate)
{
$this->amount = $amount;
$this->currency = $currency;
$this->dueDate = $dueDate;;
if ($dueDate instanceof \DateTime) {
$this->dueDate = $dueDate->format(\DateTime::ATOM);
}
}
yet it doesn't feel entirely right, and I am curious if I could configure the serialize process differently, in the sense, instead of coding my representation, modify the way the object is serialized.
Reasoning is to have all \DateTime objects serialized that are serialized wherever in an to-be-serialized object in a same specific way, without duplicating logic. (I guess I could put the handling in an abstract class or somewhere similar, yet extending objects also has its pitfalls)
Basically:
Is there a catch an onserialize "event" where I can add some logic, or am I better off looking into JMSSerializer?
JsonSerializableclass and create a method namedjsonSerializethat returns an array of the data you want serialized by thejson_encode()function