Skip to content

Instantly share code, notes, and snippets.

@ixti
Created June 2, 2010 13:04
Show Gist options
  • Save ixti/422331 to your computer and use it in GitHub Desktop.
Save ixti/422331 to your computer and use it in GitHub Desktop.
<?php // file: library/App/Record/Filter/Date.php
/** Doctrine_Record_Filter */
require_once 'Doctrine/Record/Filter.php';
class App_Record_Filter_Date extends Doctrine_Record_Filter
{
protected $_format = null;
protected $_fields = array();
// Thanks to Dave Small for pointig out problem with YYYY format
public function __construct($format = 'yyyy-MM-dd')
{
$this->_format = $format;
}
public function init()
{
$table = $this->getTable();
foreach ($table->getColumns() as $name => $opts) {
if ('date' === $opts['type']) {
$fieldName = $table->getFieldName($name);
$table->removeColumn($name);
$table->setColumn($name . ' as __' . $fieldName, 'date', $opts['length'], $opts);
$this->_fields[$fieldName] = '__' . $fieldName;
}
}
}
public function filterSet(Doctrine_Record $record, $name, $value)
{
if ((null !== $value) && isset($this->_fields[$name])) {
if ($value instanceof Zend_Date) {
$value = $value->toString($this->_format);
}
if (Zend_Date::isDate($value, $this->_format)) {
$record[$this->_fields[$name]] = $value;
}
return $record;
}
throw new Doctrine_Record_UnknownPropertyException(sprintf('Unknown record property / related component "%s" on "%s"', $name, get_class($record)));
}
public function filterGet(Doctrine_Record $record, $name)
{
if (isset($this->_fields[$name])) {
$value = $record[$this->_fields[$name]];
return ($value && Zend_Date::isDate($value)) ? new Zend_Date($value, $this->_format) : $value;
}
throw new Doctrine_Record_UnknownPropertyException(sprintf('Unknown record property / related component "%s" on "%s"', $name, get_class($record)));
}
}
<?php file: models/Person.php
class Person extends Doctrine_Record
{
public function setTableDefinition()
{
$this->hasColumn('birthday', 'date');
}
public function setUp()
{
$this->unshiftFilter(new App_Record_Filter_Date);
}
}
<?php file: test.php
// some init processes:
$person = new Person;
$person->birthday = new Zend_Date;
$person->save();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment