pugx/shortid-php

An implementation of shortid in PHP

v0.3.1 2017-09-29 09:20 UTC

README

Total Downloads Build Status Code Climate Test Coverage SensioLabsInsight

This library is an implementation of ShortId for PHP.

Basic usage

Just call PUGX\Shortid\Shortid::generate() to get a random string with default length 7, like "MfiYIvI".

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$id = Shortid::generate();

Advanced usage

In the following example, you can see how to change the basic alphabet and default length.

Default alphabet uses all letters (lowercase and uppercase), all numbers, underscore, and hypen.

use PUGX\Shortid\Factory;
use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$factory = new Factory();
// alphabet string must be 64 characters long
$factory->setAlphabet('é123456789àbcdefghìjklmnòpqrstùvwxyzABCDEFGHIJKLMNOPQRSTUVWX.!@|');
// length must be between 2 and 20 (default is 7)
// of course, a lower length is increasing clashing probability
$factory->setLength(9);
Shortid::setFactory($factory);

$id = Shortid::generate();

As alternative, you can customize single generations:

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$id9 = Shortid::generate(9, 'é123456789àbcdefghìjklmnòpqrstùvwxyzABCDEFGHIJKLMNOPQRSTUVWX.!@|');
$id5 = Shortid::generate(5);

Pre-defined values

If you need a deterministic string, instead of a random one, you can call directly the class constructor. This could be useful, for instance, when you need pre-defined data for testing purposes.

use PUGX\Shortid\Shortid;

require_once __DIR__.'/vendor/autoload.php';

$myFixedId = new Shortid('5h0r71d');
$anotherFixedId = new Shortid('fooBarZ');

Doctrine

If you want to use ShortId with Doctrine ORM, take a look to ShortId Doctrine type.

Doctrine and Symfony

If you want to use ShortId with Doctrine ORM and Symfony framework, take a look to ShortId Doctrine type bundle.