PHP code example of dynamikaweb / yii2-uuid

1. Go to this page and download the library: Download dynamikaweb/yii2-uuid library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

dynamikaweb / yii2-uuid example snippets


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

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

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

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

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

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

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

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;
}

use dynamikaweb\uuid\UuidMask;

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

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