dynamikaweb/yii2-uuid

Guide and package for using UUID in yii2 projects

Installs: 499

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Type:yii2-extension

1.1 2021-11-11 16:28 UTC

This package is auto-updated.

Last update: 2024-02-20 00:03:56 UTC


README

Latest Stable Version Total Downloads License Codacy Badge Build Test Latest Unstable Version

Installation

The preferred way to install this extension is through composer.

Either run

$ composer require dynamikaweb/yii2-uuid "*"

or add

"dynamikaweb/yii2-uuid": "*"

to the require section of your composer.json file.

Database usage

Create migration

public function safeUp()
{
    $this->addColumn('sometable', 'uuid', 'uuid' => $this->binary(16)->unique()->notNull());
    $this->createIndex('sometable_uuid_idx', 'sometable', 'uuid');
    ...
}

Model usage

Validate

use dynamikaweb\uuid\UuidValidator;
public function rules()
{
    return [
        [['uuid'], UuidValidator::classname(), 'on' => self::SCENARIO_SEARCH]
        ...
    ];
}

Generate and save

use dynamikaweb\uuid\Uuid;
public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    if ($this->isNewRecord) {
        $this->setAttribute('uuid', Uuid::uuid4()->getBytes());
    }
    ...
}

Formatting to string

public function getUuidToString()
{
    if (is_resource($this->uuid)) {
        $this->uuid = stream_get_contents($this->uuid);
    }

    return Uuid::fromBytes($this->uuid)->toString();
}

Controller usage

View

public function actionView($uuid)
{
    return $this->render('view', [
        'model' => $this->findModel($uuid)
    ]);
}

Finding

protected function findModel($uuid)
{
    try {
        $uuid = '\x'.bin2hex(Uuid::fromString($uuid)->getBytes());
    }
    catch (InvalidUuidStringException $e) {
        throw new HttpException(400, 'UUID invalid!');
    }
    if (($model = SomeModel::findOne(['uuid' => $uuid])) === null) {
        throw new HttpException(404, 'UUID not found!');
    } 
    
    return $model;
}

View usage

Form

use dynamikaweb\uuid\UuidMask;

echo UuidMask::widget([
    'name' => 'uuid'
]);

Active form

echo $form->field($model, 'from_date')->widget(Uuid::className());