I want to be able to get and set the date using my own date format (dd/mm/yyyy) and not doctrine (yyyy-mm-dd). I've found a way that is specifying a getter and setter for every date field however I want do it in a more convenient way (1 setter + 1 getter for ev开发者_开发技巧ery date field in every table is a lot)
class Curs extends BaseCurs {
private function fechaDesdeEsp($fecha){
$fecha = new DateTime($fecha);
return $fecha->format('Y-m-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'));
}
}
Hope you find a solution, Thanks in Advance
I've 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 who has timestamp fields:
/// models/MyModel.php
abstract class MyModel extends Doctrine_Record{
public function setTableDefinition(){
// [...]
}
public function setUp(){
parent::setUp();
$this->actAs("DateFormatTemplate");
// [...]
}
}
I think you could try overriding __call
, which handles Doctrine's automatic get/set stuff, and maybe __get
and __set
too. Then, in those functions, look at the table's metadata (you should be able to get to this via getTable()
and a method on the table class). The metadata contains the type of the column, so just test whether this is of the type you want or not.
This way you can just have the overrides for the magic methods and they should handle it for you. I recall you could also put this in a custom class which inherits from Doctrine_Record, and then modify Doctrine's model generator settings so that it uses your custom record class as the base.
Look at Doctrine's API documentation (or their source code, it's pretty clean) to find out the specifics I forgot :)
精彩评论