dynamikaweb/yii2-uuid

使用 UUID 的 yii2 项目指南和包

安装: 680

依赖关系: 0

建议者: 0

安全性: 0

星星: 0

关注者: 1

分支: 0

类型:yii2-extension

1.1 2021-11-11 16:28 UTC

This package is auto-updated.

Last update: 2024-09-20 01:12:44 UTC


README

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

安装

安装此扩展的首选方式是通过 composer

运行以下命令之一:

$ composer require dynamikaweb/yii2-uuid "*"

或者

"dynamikaweb/yii2-uuid": "*"

将以下内容添加到您的 composer.json 文件的 require 部分:

数据库使用

创建迁移

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