How to generate an universally unique identifier (UUID) in Symfony 3

Till the date, unlike standards versions of Python or Java, PHP doesn't offer an easy way to natively generate Universal Unique Identifiers. Some developers can rely on easy formats like the generated by uniqd or included hash algorithms. In some cases you will need to generate those identifiers only with PHP and without relying on extra CLI tools, fortunately for you, there's an useful library written totally in PHP that can help you with this.

We are talking about the UUID Library by Ramsey, this library allows you to generate and work with RFC 4122 version 1, 3, 4, and 5 universally unique identifiers (UUID). You can use this library on your Symfony 3 project easily with composer and we'll show you how in this article.

1. Install UUID package

As first step, you need to install the library with composer, so open the command line, switch to the directory of your project and execute the following command:

composer require ramsey/uuid

For more information about this library, please visit the official repository at Github here.

2. Using the library

Basically the library exposes the Uuid class in the Ramsey\Uuid namespace, so you only need to include in your controller. The class offers 4 static methods, one for every UUID type with the respective nomenclature e.g uuid1, uuid3, uuid4 and uuid5:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

// Include Library Namespaces
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;

class DefaultController extends Controller
{
    /**
     * @Route("/", name="homepage")
     */
    public function indexAction(Request $request)
    {
        try {
            // Generate a version 1 (time-based) UUID object
            $uuid1 = Uuid::uuid1();

            // e.g ba51070a-d754-11e7-b225-4ccc6ab413a6
            echo $uuid1->toString() . "<br>";
        
            // Generate a version 3 (name-based and hashed with MD5) UUID object
            $uuid3 = Uuid::uuid3(Uuid::NAMESPACE_DNS, 'php.net');

            // e.g 11a38b9a-b3da-360f-9353-a5a725514269
            echo $uuid3->toString() . "<br>";
        
            // Generate a version 4 (random) UUID object
            $uuid4 = Uuid::uuid4();

            // e.g 0e9139c5-8e06-4a1a-bb5e-52a0abcd0072
            echo $uuid4->toString() . "<br>";
        
            // Generate a version 5 (name-based and hashed with SHA1) UUID object
            $uuid5 = Uuid::uuid5(Uuid::NAMESPACE_DNS, 'php.net');

            // e.g c4a760a8-dbcf-5254-a0d9-6a4474bd1b62
            echo $uuid5->toString() . "<br>";

            return new Response();
        } catch (UnsatisfiedDependencyException $e) {
            // Some dependency was not met. Either the method cannot be called on a
            // 32-bit system, or it can, but it relies on Moontoast\Math to be present.
            throw new HttpException(500, 'Caught exception: ' . $e->getMessage());
        }
    }
}

The library mentions that unless you are making an advanced usage for it to generate identifiers that deviate from RFC 4122, you probably do not want to instantiate the UUID class directly but using the static methods instead.

Known Exceptions

While you install and test the library, you may face some exceptions (the unmet dependencies) in our previous try-catch block:

When calling Ramsey\Uuid\Converter\Time\DegradedTimeCnverter::calculateTime on a 32-bit system, Moontoast\Math\BigNumber must be present.

This error is caused due to a mathematic feature that can be achieved in 32-bit based systems. This happens because a UUID is an unsigned 128-bit integer, and the time portion of a version 1 UUID is an unsigned 64-bit number. PHP on a 32-bit system only supports signed integers up to 2147483647. You can solve it easily installing the BigNumber package for PHP with composer:

composer require moontoast/math

This library is useful for working with integers that are larger than (or may become larger than, through mathematical computations) PHP's max integer value for a given system. On 64-bit systems, this number is 9223372036854775807. On 32-bit systems, it is 2147483647. When overflowing this boundary, PHP turns the number into a float, reducing precision (see the PHP manual entry for Integers). For more information about this package visit the official repository in Github hereAfter installing this package you should be able to generate the UUID normally. If you know another exception that you may face with this library, please share it with the community in the comment box.

Happy coding !

This could interest you

Become a more social person