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