Skip to content

Instantly share code, notes, and snippets.

@Sitebase
Created February 22, 2013 13:48
Show Gist options
  • Save Sitebase/5013494 to your computer and use it in GitHub Desktop.
Save Sitebase/5013494 to your computer and use it in GitHub Desktop.
Custom doctrine type to store uuid's as binary(16) values in a MySQL database. Set the column type that you want to use as BINARY(16) in MySQL and your good to go.
\Doctrine\DBAL\Types\Type::addType('uuid', 'BuboBox\Doctrine2\DBAL\Types\UuidType');
<?php
namespace BuboBox\Doctrine2\DBAL\Types;
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
/**
* Type that maps a PHP array to a clob SQL type.
*
* @since 2.0
*/
class UuidType extends Type
{
const BINARY = 'binary';
public function getSqlDeclaration(array $fieldDeclaration, AbstractPlatform $platform)
{
return sprintf('BINARY(%d)', $fieldDeclaration['length']);
}
public function getName()
{
return self::BINARY;
}
public function convertToPhpValue($value, AbstractPlatform $platform)
{
if ($value !== null) {
$value= unpack('H*', $value);
$hash = array_shift($value);
$uuid = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
return $uuid;
}
}
public function convertToDatabaseValue($value, AbstractPlatform $platform)
{
if ($value !== null) {
return pack('H*', str_replace('-', '',$value));
}
}
}
@ricbra
Copy link

ricbra commented Jun 26, 2015

Thanks for sharing this! Perhaps you want to checkout my fork as I've slightly updated the code a bit. For the reasoning behind this you might wanna checkout the post I wrote about it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment