Overriding nette/utils/ class

gfeep
Member | 5
+
0
-

Hello, I am using Nette v2.4, and I somehow need to modify json output of datetime fields in the WHOLE application which comes from

Nette\Utils\DateTime

any advice how to (or whether it is even possible) extend above mentioned class with my own class (below) to be used in the whole project? I have been trying some alterations in config.neon using services, but I have not been successful yet.

namespace My\Own\Namespace;

class DateTime extends \Nette\Utils\DateTime
{

    public function jsonSerialize()
    {
	    return SOMETHING....;
    }
}

Thanks for any kind of advice

Mistrfilda
Member | 76
+
0
-

Hello,

You can extend Nette\Utils\DateTime and overide jsonSerialize. But It depends, on how you work with these dates and in which context you need json output. Are you creating dates in some datetime factory class (in nette DI container)? Or just simply new \Nette\Utils\DateTime() everytime in code? If you are using datetime factory, then it would be easy change to your new datetime class but If you are creating instances in code via new and there is a lot of these lines, propably easist and the fastest way is to create some service/static formater which takes Nette\Utils\DateTime as parameter and returns desired json format. But again, it really depends on in which case you need that json output.

Last edited by Mistrfilda (2020-08-05 13:10)

gfeep
Member | 5
+
0
-

hello @Mistrfilda ,

I don't do anything special. Fetching data from DB and exposing them to API.

If any of those dtaa fetched from DB is datetime/timestamp, Nette will automatically transform it to Nette\Utils\DateTime. Afterwards, when data are being exposed via JSON, it will transform my date value per definition of jsonSerialize(). That's why I mentioned that I'd need to apply this in my whole project without any brutal interventions.

Thanks.

Mistrfilda
Member | 76
+
0
-

Sorry, i am not really familiar with nette/database package but if I am looking at correct classes, I dont think its possible to change default datetime class to some other instance in config or any other place – https://github.com/…esultSet.php#L154 There was PR for something similiar – https://github.com/…ase/pull/138 but I dont think it got merged.

BigCharlie
Member | 283
+
0
-

It looks like your problem is to return database date in custom format via JSON.

How about to read database data to an object, that implements JsonSerializable interface? That would help you return that object and you are able to customize serialization.

Or you can use JMS Serializer