【问题标题】:Doctrine: Change date format when getting and setting field values原则:获取和设置字段值时更改日期格式
【发布时间】:2010-08-03 01:15:51
【问题描述】:

我希望能够使用我自己的日期格式 (dd/mm/yyyy) 而不是教条getset日期(yyyy-mm-dd)。我找到了一种为 每个日期字段 指定 gettersetter 的方法,但是我想以更方便的方式进行(每个表中每个日期字段的 1 个 setter + 1 个 getter 很多)

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'));
    }

}

希望您能找到解决方案,在此先感谢

【问题讨论】:

    标签: php doctrine


    【解决方案1】:

    我发现这对我来说是最好的解决方案:

    /// 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);
        }
    
    }
    

    那么,每个拥有时间戳字段的模型:

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

    【讨论】:

      【解决方案2】:

      我认为您可以尝试覆盖 __call,它处理 Doctrine 的自动获取/设置内容,也许还有 __get__set。然后,在这些函数中,查看表的元数据(您应该能够通过getTable() 和表类上的方法来获得它)。元数据包含列的类型,因此只需测试它是否属于您想要的类型。

      通过这种方式,您可以只使用魔术方法的覆盖,它们应该为您处理它。我记得你也可以把它放在一个继承自 Doctrine_Record 的自定义类中,然后修改 Doctrine 的模型生成器设置,以便它使用你的自定义记录类作为基础。

      查看 Doctrine 的 API 文档(或它们的源代码,非常干净)找出我忘记的细节 :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-03
        相关资源
        最近更新 更多