我想在数据库中保存一个使用原则模式工具创建的日期时间。在我的表单中,我设置了一个日期和时间,我想把它保存为数据库中的日期时间。
所以我试了这个:
$e->setStartDateTime(new Zend_Date('2011-09-01T22:00:00',Zend_date::DATETIME));
但是我得到错误:
PHP Fatal error: Call to undefined method Zend_Date::format() in /var/www/shared/Doctrine/lib/vendor/doctrine-dbal/lib/Doctrine/DBAL/Types/DateTimeType.php on line 44
谁有这方面的经验,能帮我解决这个问题? 你可以重写原生数据类型,使用Zend_Date代替PHP的原生DateTime,这是Doctrine数据类型' DateTime ', 'time'和'date'的默认值。
首先在你的应用程序Bootstrap文件中,在你实例化你的Doctrine EntityManager之前添加以下内容。这个代码应该排在任何其他教义代码之前:
Doctrine'DBAL'Types'Type::overrideType('datetime', 'yournamespace'types'DateTimeType');
Doctrine'DBAL'Types'Type::overrideType('date', 'yournamespace'types'DateType');
Doctrine'DBAL'Types'Type::overrideType('time', 'yournamespace'types'Time');
现在只需要实现这3个类。最简单的方法就是扩展相应的Doctrine类来实现这一点。代码实际上是相同的所有3个类,唯一的区别是你从类和你的类的名称扩展。下面是DateTimeType类的例子:
namespace yournamespace'type;
use Doctrine'DBAL'Types'DateTimeType as DoctrineDateTimeType;
use Doctrine'DBAL'Platforms'AbstractPlatform;
/**
* Override 'datetime' type in Doctrine to use Zend_Date
*/
class DateTimeType extends DoctrineDateTimeType
{
/**
* Convert from db to Zend_Date
*
* @param string $value
* @param AbstractPlatform $platform
* @return 'Zend_Date|null
*/
public function convertToPhpValue($value, AbstractPlatform $platform)
{
if (is_null($value)) {
return null;
}
'Zend_Date::setOptions(array('format_type' => 'php', ));
$phpValue = new 'Zend_Date($value, $platform->getDateTimeFormatString());
'Zend_Date::setOptions(array('format_type' => 'iso', ));
return $phpValue;
}
/**
* Convert from Zend_Date to db
*
* @param string $value
* @param AbstractPlatform $platform
* @return string|null
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (is_null($value)) {
return null;
}
'Zend_Date::setOptions(array('format_type' => 'php', ));
$dbValue = $value->toString($platform->getDateTimeFormatString());
'Zend_Date::setOptions(array('format_type' => 'iso', ));
return $dbValue;
}
}
现在你仍然可以在Doctrine中使用@Column(type="datetime")注释。当保存到数据库时,您可以将"datetime"类型的实体属性保存到Zend_Date实例中。同样,当从数据库中抓取实体时,"datetime"类型的属性现在将是Zend_Dates。
Doctrine2期望PHP DateTime对象用于DQL日期和日期时间类型。
如果您不强制使用Zend_Date,则改为:
->setStartDateTime(new DateTime('2011-09-01T22:00:00'))
否则,转换为DateTime:
new DateTime('@' . $zendDate->getTimestamp())
参见DateTime
docs
您可以实现自定义映射类型或使用此ZendDateType实现。