Skip to content

dynamikaweb/yii2-uuid

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

dynamikaweb/yii2-uuid

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());

About

Guide and package for using UUID in yii2 projects

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages