原则:获取和设置字段值时更改日期格式 [英] Doctrine: Change date format when getting and setting field values

查看:109
本文介绍了原则:获取和设置字段值时更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用自己的日期格式( dd / mm / yyyy 设置日期,而不是教义( YYYY-MM-DD )。我已经找到了一种方式来为每个日期字段指定 getter setter ,但是我想以更方便的方式(<每个表中每个日期字段的1个setter + 1个getter是很多)

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 every 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");
        // [...]
     }

}

这篇关于原则:获取和设置字段值时更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆