使用Doctrine 2.1将Zend日期保存在数据库中

san*_*ers 2 php zend-framework zend-date doctrine-orm

我想在使用doctrine模式工具创建的数据库中保存日期时间.在我的表单中,我设置了日期和时间,我想将其保存为数据库中的日期时间.

所以我试过这个:

$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
Run Code Online (Sandbox Code Playgroud)

有没有人有这方面的经验,能够帮助我解决这个问题?

Luk*_*ley 5

您可以覆盖本机数据类型以使用Zend_Date而不是PHP的本机DateTime,这是Doctrine数据类型'datetime','time'和'date'的默认值.

首先在您的应用程序Bootstrap文件中,在实例化Doctrine EntityManager之前添加以下内容.此代码应该在任何其他Doctrine代码之前:

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');
Run Code Online (Sandbox Code Playgroud)

现在您只需要实现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;
    }

}
Run Code Online (Sandbox Code Playgroud)

现在你仍然可以在Doctrine中使用@Column(type ="datetime")注释.保存到数据库时,可以将类型为"datetime"的实体属性保存到Zend_Date实例.此外,当从数据库中抓取实体时,"datetime"类型的属性现在将是Zend_Dates.