数据迁移组件三:自定义数据字段类型
[Doctrine Migrations]数据库迁移组件的深入解析三:自定义数据字段类型
自定义type
根据官方文档,新建TinyIntType类,集成Type,并重写getName
,getSqlDeclaration
,convertToPHPValue
,getBindingType
等方法。
TinyIntType.php完整代码:
<?php
namespace db\types;
use Doctrine\DBAL\ParameterType;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\Type;
/**
* 扩展DBAL组件类型
*
* 迁移组件依赖的DBAL组件默认并不支持tinyint类型
* 此类是为mysql支持tinyint类型而扩展的类
*
* @author tangbo<admin@tbphp.net>
*/
class TinyIntType extends Type
{
public function getName()
{
return 'tinyint';
}
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
$sql = 'TINYINT';
if (is_numeric($fieldDeclaration['length']) && $fieldDeclaration['length'] > 1) {
$sql .= '(' . ((int) $fieldDeclaration['length']) . ')';
} else {
$sql .= '(3)';
}
if (!empty($fieldDeclaration['unsigned'])) {
$sql .= ' UNSIGNED';
}
if (!empty($fieldDeclaration['autoincrement'])) {
$sql .= ' AUTO_INCREMENT';
}
return $sql;
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return (null === $value) ? null : (int) $value;
}
public function getBindingType()
{
return ParameterType::INTEGER;
}
}