Search This Blog

Monday, February 4, 2013

Symfony 2 / Doctrine Support Enum Data types.

These posts were followed to add enum support to this Symfony 2 project:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/mysql-enums.html, http://symfony.com/doc/2.0/reference/configuration/doctrine.html.
This post is to document the steps done to implement it, under Symfony 2.2.0

1. Add dbal configration in app/config/config.yml



doctrine:
    dbal:
        driver:   %database_driver%
        host:     %database_host%
        port:     %database_port%
        dbname:   %database_name%
        user:     %database_user%
        password: %database_password%
        charset:  UTF8
        mapping_types:
            enum: string
        types:
            enumservermonitor: JMPR\ServerMonBundle\Type\EnumServerMonitorType
            enumserverstatus: JMPR\ServerMonBundle\Type\EnumServerStatusType
            enumalertaction: JMPR\ServerMonBundle\Type\EnumAlertActionType

2. Create the column class types.

As specified in the config.yml file the Enum...Type classes are created.

The EnumServerMonitor type is below.
It does the following:
  • defines a classname and the enum values (service/website/host).
  • specifies the sql declaration.
  • defines 2 methods to convert the value to php from the database and from php to the database value.

<?php
namespace JMPR\ServerMonBundle\Type;

use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;

class EnumServerMonitorType extends Type
{
    const ENUM_SERVERMONITOR = 'enumservermonitor';
    const VALUE_SERVICE = 'service';
    const VALUE_WEBSITE = 'website';
    const VALUE_HOST = 'host';

    public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
    {
        return "enum('service','website','host') NOT NULL default 'service' COMMENT '(DC2Type:enumservermonitor)'";
    }

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return $value;
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        if (!in_array($value, array(self::VALUE_SERVICE, self::VALUE_WEBSITE, self::VALUE_HOST))) {
            throw new \InvalidArgumentException("Invalid monitor type");
        }
        return $value;
    }

    public function getName()
    {
        return self::ENUM_SERVERMONITOR;
    }
}



No comments:

Post a Comment