Yii 2 UUID Helper
UUID Helper and validator for Yii 2., (*1)
This library interfaces with ramsey/uuid to
generate
universally unique identifiers., (*2)
For license information check the LICENSE-file., (*3)
, (*4)
Installation
The preferred way to install this extensions is through composer., (*5)
Either run, (*6)
php composer.phar require --prefer-dist thamtech/yii2-uuid
or add, (*7)
"thamtech/yii2-uuid": "*"
to the require
section of your composer.json
file., (*8)
Usage
New UUID
Generate a new UUID (version 4 by default):, (*9)
$uuid = \thamtech\uuid\helpers\UuidHelper::uuid();
Ad-Hoc Validation
Validate that a string is formatted in the canonical format using
hexadecimal text with inserted hyphen characters (case insensitive):, (*10)
$uuid = 'de305d54-75b4-431b-adb2-eb6b9e546014';
$isValid = \thamtech\uuid\helpers\UuidHelper::isValid($uuid); // true
$uuid = 'not-a-uuid';
$isValid = \thamtech\uuid\helpers\UuidHelper::isValid($uuid); // false
// or using the Validator class directly
$validator = new \thamtech\uuid\validators\UuidValidator();
if ($validator->validate($uuid, $error)) {
// valid
} else {
// not valid
echo $error
}
Or you can include the use
lines, especially if you will be making multiple
uuid calls within a file:, (*11)
use thamtech\uuid\helpers\UuidHelper;
use thamtech\uuid\helpers\UuidValidator;
// ...
$uuid = 'de305d54-75b4-431b-adb2-eb6b9e546014';
$isValid = UuidHelper::isValid($uuid); // true
$uuid = 'not-a-uuid';
$isValid = UuidHelper::isValid($uuid); // false
// or using the Validator class directly
$validator = new UuidValidator();
if ($validator->validate($uuid, $error)) {
// valid
} else {
// not valid
echo $error
}
Field Validation
Incorporate this same validation into your model:, (*12)
public function rules()
{
return [
[['uuid'], 'thamtech\uuid\validators\UuidValidator'],
];
}
See Also