Symfony News

Introducing the new Symfony UUID Polyfill

Grégoire Pineau

Contributed by
Grégoire Pineau
in #197.

A UUID (Universally unique identifier) is a 128-bit number used to identify information in computer systems. They are becoming increasingly popular in PHP/Symfony applications, where some developers use them even as IDs for database records (instead of the traditional auto increment integer).

There are different variants and versions of UUIDs, so most developers rely on external libraries such as the UUID PECL package and the ramsey/uuid library to generate these UUIDs.

Symfony Polyfills provide PHP reimplementations of popular functions, classes and constants introduced in newer PHP versions or PHP extensions. They allow for example to use the PHP 7.3 JsonException class in any PHP version or the PHP 7.4 password_algos() function in any previous PHP version.

Given the popularity of UUIDs, we've created a new UUID polyfill that reimplements the UUID PECL package and can be used in PHP 5.3 or higher. First, install the polyfill in your project:

1
$ composer require symfony/polyfill-uuid

If the UUID PECL package is installed in your system, this polyfill does nothing. Otherwise, it defines the exact same constants and functions of the PECL package so you can use the following in your code:

1
2
3
4
5
6
7
8
$uuid = uuid_create(Uuid::UUID_TYPE_RANDOM);
// $uuid = '79a0f84a-2f15-4ea9-bb2c-49e645845100'

$isValid = uuid_is_valid($uuid);
// $isValid = true

// Other useful functions: uuid_compare(), uuid_is_null(), uuid_type(),
// uuid_variant(), uuid_time(), uuid_mac(), uuid_parse(), uuid_unparse()

The UUID Polyfill can replace the UUID PECL package entirely when you can't or don't want to install the PECL package. However, it doesn't provide (and it'll never provide) the same features of full-featured libraries such as ramsey/uuid.

Regarding performance, the polyfill is faster or slower than the PECL package depending on the UUID version being created:

Time to create UUID v1 Mean Difference
PECL 0.525μs Fastest
Symfony Polyfill 1.401μs 2.67x slower
Ramsey/UUID 3.907μs 7.45x slower
Time to create UUID v4 Mean Difference
PECL 4.620μs 3.25x slower
Symfony Polyfill 1.422μs Fastest
Ramsey/UUID 1.851μs 1.30x slower

Be trained by Symfony experts - 2019-12-2 Berlin - 2019-12-2 Berlin - 2019-12-2 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook