What do you use instead of ENUM in Doctrine2? smallint? I thought of using varchar, or explicitly define char, but this may not be very effective when it comes to indexes, or am I wrong?
I usually work with integers mapped to class constants, like
class MyEntity {
const STATUS_INACTIVE = 0;
const STATUS_ACTIVE = 1;
const STATUS_REFUSE = 2;
protected $status = self::STATUS_ACTIVE;
}
That works quite fine and makes it even easier to work with what you would call ENUMS in an IDE.
You can also use an enumerable type as described by the documentation, but that means you will have to define one custom type per enum column. That's a lot of work with no real benefit.
You may also want to know why you shouldn't really use enums.
Postgres, Symfony, ORM, Doctrine...
Postgres: Define new type enum (pgAdmin)
CREATE TYPE new_enum AS ENUM ('sad', 'ok', 'happy');
In Entity
@ORM\Column(name="name", type="string", columnDefinition="new_enum",
nullable=true)
In config.yml
mapping_types:
new_enum: string
# Doctrine Configuration
doctrine:
dbal:
driver: "%database_driver%"
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
mapping_types:
new_enum: string # <=======
If you want MySQL ENUMs using MySQL and Symfony, you can now use an easy way for that without any dependencies
<?php
namespace App\Enum;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
abstract class EnumType extends Type
{
protected $name;
protected $values = [];
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
$values = array_map(function($val) { return "'".$val."'"; }, $this->values);
return "ENUM(".implode(", ", $values).")";
}
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return $value;
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if (!in_array($value, $this->values)) {
throw new \InvalidArgumentException("Invalid '".$this->name."' value.");
}
return $value;
}
public function getName()
{
return $this->name;
}
public function requiresSQLCommentHint(AbstractPlatform $platform)
{
return true;
}
}
namespace App\Enum;
class UploadFileStatusType extends EnumType
{
const OPEN = 'open';
const DONE = 'done';
const ERROR = 'error';
protected $name = self::class;
protected $values = [
self::OPEN => self::OPEN ,
self::DONE => self::DONE,
self::ERROR => self::ERROR,
];
}
doctrine:
dbal:
types:
UploadFileStatusType: App\Enum\UploadFileStatusType
class MyEntity
{
/**
* @var string
*
* @ORM\Column(type="UploadFileStatusType")
*/
protected $status;
}
enum('open', 'done', 'error')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With