Doctrine: changing the date format when receiving and setting field values

I want to get and set the date using my own date format (dd / mm / yyyy) and not doctrine (yyyy-mm-dd), I found a way defining getter and setter for each date field , but I want to do this is a more convenient way (1 setter + 1 getter for each date field in each table a lot)

class Curs extends BaseCurs { private function fechaDesdeEsp($fecha){ $fecha = new DateTime($fecha); return $fecha->format('Ym-d'); } private function fechaDesdeIso($fecha){ $fecha = new DateTime($fecha); return $fecha->format('d/m/Y'); } public function setFechainici($fecha_inici) { return $this->_set('fecha_inici', $this->fechaDesdeEsp($fecha_inici)); } public function getFechainici() { return $this->fechaDesdeIso($this->_get('fecha_inici')); } } 

We hope you find a solution, thanks in Advance

+4
source share
2 answers

I found this to be the best solution for me:

 /// models/DateFormatBehaior.php class DateFormatListener extends Doctrine_Record_Listener{ public function preInsert(Doctrine_event $Event){ $this->_prepare_date($Event); } public function preUpdate(Doctrine_event $Event){ $this->_prepare_date($Event); } // Private stuff private function _prepare_date(Doctrine_event $Event){ $Model = $Event->getInvoker(); foreach($Model->getTable()->getColumns() as $FieldName=>$Field){ if($Field['type']=='timestamp'){ if(preg_match("/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/",$Model[$FieldName],$Matches)){ $Model->$FieldName = sprintf("%s-%s-%s 00:00:00",$Matches[3],$Matches[2],$Matches[1]); // YYYY-DD-MM HH:MM:SS } } } } } class DateFormatTemplate extends Doctrine_Template{ public function setTableDefinition(){ $this->addListener(new DateFormatListener); } } 

Then each model that has timestamps:

 /// models/MyModel.php abstract class MyModel extends Doctrine_Record{ public function setTableDefinition(){ // [...] } public function setUp(){ parent::setUp(); $this->actAs("DateFormatTemplate"); // [...] } } 
+4
source

I think you could try to override __call , which handles Doctrine automatically get / set stuff and maybe __get and __set too. Then, in these functions, view the table metadata (you can get this via getTable() and the method in the table class). Metadata contains the type of the column, so just check to see if it is the type you need.

That way, you can simply override magic methods, and they should handle it for you. I remember, you could also put this in a custom class that inherits from Doctrine_Record, and then modify the settings of the Doctrine model generator so that it uses your own record class as the base.

Take a look at the Doctrine API documentation (or their source code, it's pretty clean) to find out the features I forgot :)

0
source

Source: https://habr.com/ru/post/1315242/


All Articles