Skip to content

Instantly share code, notes, and snippets.

@serapheem
Created July 25, 2013 15:18
Show Gist options
  • Save serapheem/6080756 to your computer and use it in GitHub Desktop.
Save serapheem/6080756 to your computer and use it in GitHub Desktop.
Doctrine 2 - Adding custom field type
# 2nd solution
# Symfony's way :-)
doctrine:
dbal:
default_connection: default
types:
sphinx_mva:
class: SomeBundle\Doctrine\Types\SphinxMvaType
commented: true
<?php
// 1st solution
namespace SomeBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Doctrine\DBAL\Types\Type;
class CormesClipkitTestBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function boot()
{
// Add sphinx_mva type
if ( ! Type::hasType('sphinx_mva')) {
Type::addType('sphinx_mva', 'Cormes\Clipkit\TestBundle\Doctrine\Types\SphinxMvaType');
}
// Add sphinx_mva type to current connection.
// Notice: during tests there can be multiple connections to db so
// it will be needed to add 'sphinx_mva' to all new connections if not defined.
/** @var \Doctrine\DBAL\Platforms\AbstractPlatform $dbPlatform */
$dbPlatform = $this->container
->get('doctrine.orm.sphinx_entity_manager')
->getConnection()
->getDatabasePlatform();
if ( ! $dbPlatform->hasDoctrineTypeMappingFor('sphinx_mva')) {
$dbPlatform->registerDoctrineTypeMapping('mva', 'sphinx_mva');
}
}
}
<?php
namespace SomeBundle\Doctrine\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
class SphinxMvaType extends Type
{
const SPHINX_MVA = 'sphinx_mva';
/**
* {@inheritdoc}
*/
public function getSQLDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return $platform->getDoctrineTypeMapping('BLOB');
// return $platform->getClobTypeDeclarationSQL($fieldDeclaration);
}
/**
* {@inheritdoc}
*/
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
return ($value === null) ? null : sprintf('(%s)', implode(',', $value));
}
/**
* {@inheritdoc}
*/
public function convertToPHPValue($value, AbstractPlatform $platform)
{
return ($value === null) ? null : explode(',', trim($value, " \t\n\r\0\x0B()"));
}
/**
* {@inheritdoc}
*/
public function getName()
{
return self::SPHINX_MVA;
}
}
<?php
namespace SomeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Video
*
* @ORM\Table(name="video")
* @ORM\Entity
*/
class Video
{
/**
* @var string
*
* @ORM\Column(type="string", length="255")
*/
private $title;
/**
* @var array
*
* @ORM\Column(type="sphinx_mva")
*/
private $channels;
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment