1、在 Github 上搜索 yii2 uuid,选择 wartron/yii2-uuid,如图1
2、基于 Composer 安装,报错
composer require wartron/yii2-uuid "*"
./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - The requested package wartron/yii2-uuid * is satisfiable by wartron/yii2-uuid[dev-master] but these conflict with your requirements or minimum-stability. Installation failed, reverting ./composer.json to its original content.
3、基于 Composer 安装,安装成功,如图2
composer require wartron/yii2-uuid "dev-master"
./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 3 installs, 0 updates, 0 removals - Installing paragonie/random_compat (v2.0.17): Downloading (100%) - Installing ramsey/uuid (2.9.0): Downloading (100%) - Installing wartron/yii2-uuid (dev-master 2202443): Cloning 2202443ac7 from cache paragonie/random_compat suggests installing ext-libsodium (Provides a modern crypto API that can be used to generate ran dom bytes.) ramsey/uuid suggests installing moontoast/math (Support for converting UUID to 128-bit integer (in string form).) ramsey/uuid suggests installing doctrine/dbal (Allow the use of a UUID as doctrine field type.) Writing lock file Generating autoload files
4、新建数据库迁移,添加 uuid 字段到 page 模型
./yii migrate/create add_uuid_to_page
5、编辑数据库迁移文件,/console/migrations/m180807_032326_add_uuid_to_page.php,设置 uuid 为唯一索引
<?php use yii/db/Migration; /** * Class m180807_032326_add_uuid_to_page */ class m180807_032326_add_uuid_to_page extends Migration { /** * {@inheritdoc} */ public function safeUp() { $this->addColumn('{{%page}}', 'uuid', $this->string(64)->notNull()->comment('通用唯一识别码')->after('id')); $this->createIndex('uc_uuid', '{{%page}}', 'uuid', $unique = true); } /** * {@inheritdoc} */ public function safeDown() { $this->dropColumn('{{%page}}', 'uuid'); } /* // Use up()/down() to run migration code without a transaction. public function up() { } public function down() { echo "m180807_032326_add_uuid_to_page cannot be reverted./n"; return false; } */ }
6、执行数据库迁移,查看表结构,基于 Gii 重新生成模型文件,如图3
./yii migrate
7、附加行为 wartron/yii2uuid/behaviors/UUIDBehavior,编辑 /common/logics/Page.php
<?php namespace common/logics; use Yii; use yii/behaviors/SluggableBehavior; use yii/behaviors/TimestampBehavior; use yii2tech/ar/softdelete/SoftDeleteBehavior; use wartron/yii2uuid/behaviors/UUIDBehavior; use yii/helpers/ArrayHelper; class Page extends /common/models/Page { const STATUS_DELETED = -1; //状态:删除 const STATUS_DISABLED = 0; //状态:禁用 const STATUS_DRAFT = 1; //状态:草稿 const STATUS_PUBLISHED = 2; //状态:发布 const SCENARIO_CREATE = 'create'; /** * @inheritdoc */ public function behaviors() { return [ 'timestampBehavior' => [ 'class' => TimestampBehavior::className(), 'attributes' => [ self::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'], self::EVENT_BEFORE_UPDATE => 'updated_at', SoftDeleteBehavior::EVENT_BEFORE_SOFT_DELETE => 'updated_at', ] ], 'slug' => [ 'class' => SluggableBehavior::className(), 'attribute' => 'title', 'ensureUnique' => true, 'immutable' => true ], 'uuid' => [ 'class' => UUIDBehavior::className(), 'column' => 'uuid' ], 'softDeleteBehavior' => [ 'class' => SoftDeleteBehavior::className(), 'softDeleteAttributeValues' => [ 'status' => self::STATUS_DELETED ], ], ]; } /** * {@inheritdoc} */ public function scenarios() { $scenarios = parent::scenarios(); $scenarios[self::SCENARIO_CREATE] = ['slug', 'title', 'body', 'view', 'status']; return $scenarios; } /** * @inheritdoc */ public function rules() { $rules = [ [['title', 'body'], 'required'], [['slug'], 'unique'], ['view', 'default', 'value' => 0], ['status', 'default', 'value' => self::STATUS_DRAFT], ]; $parentRules = parent::rules(); unset($parentRules[0]); return ArrayHelper::merge($rules, $parentRules); } /** * {@inheritdoc} * @return PageQuery the active query used by this AR class. */ public static function find() { return new PageQuery(get_called_class()); } }
8、在 Postman 中 POST http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/pages ,报错:iconv(): Detected an illegal character in input string
{ "name": "Exception", "message": "iconv(): Detected an illegal character in input string", "code": 0, "type": "Exception", "file": "E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Client.php", "line": 383, "stack-trace": [ "#0 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Client.php(477): Hprose//Client->decode('Es54/"iconv(): D...', Array, Object(stdClass))", "#1 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Client.php(489): Hprose//Client->syncInvokeHandler('page_create', Array, Object(stdClass))", "#2 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Client.php(103): Hprose//Client->invokeHandler('page_create', Array, Object(stdClass))", "#3 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Client.php(608): Hprose//Client->Hprose//{closure}('page_create', Array, Object(stdClass))", "#4 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//hprose//hprose//src//Hprose//Proxy.php(91): Hprose//Client->invoke('page_create', Array)", "#5 E://wwwroot//github-shuijingwan-yii2-app-advanced//common//logics//rpc//Page.php(83): Hprose//Proxy->__call('page_create', Array)", "#6 E://wwwroot//github-shuijingwan-yii2-app-advanced//api//rests//page//CreateAction.php(68): common//logics//rpc//Page->create(Array, '0.0', 'zh-CN')", "#7 [internal function]: api//rests//page//CreateAction->run()", "#8 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//yiisoft//yii2//base//Action.php(94): call_user_func_array(Array, Array)", "#9 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//yiisoft//yii2//base//Controller.php(157): yii//base//Action->runWithParams(Array)", "#10 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//yiisoft//yii2//base//Module.php(528): yii//base//Controller->runAction('create', Array)", "#11 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//yiisoft//yii2//web//Application.php(103): yii//base//Module->runAction('v1/page/create', Array)", "#12 E://wwwroot//github-shuijingwan-yii2-app-advanced//vendor//yiisoft//yii2//base//Application.php(386): yii//web//Application->handleRequest(Object(yii//web//Request))", "#13 E://wwwroot//github-shuijingwan-yii2-app-advanced//api//web//index.php(17): yii//base//Application->run()", "#14 {main}" ] }
9、实现行为 /common/behaviors/UUIDBehavior.php,继承至 /wartron/yii2uuid/behaviors/UUIDBehavior,将包含数据的二进制字符串转换为十六进制值,且转化为大写
<?php namespace common/behaviors; use wartron/yii2uuid/helpers/Uuid; class UUIDBehavior extends /wartron/yii2uuid/behaviors/UUIDBehavior { public function createUUID() { return Uuid::uuid2str(parent::createUUID()); } }
10、附加行为 common/behaviors/UUIDBehavior,编辑 /common/logics/Page.php
use common/behaviors/UUIDBehavior;
11、在 Postman 中 POST http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/pages ,响应成功
{ "code": 10000, "message": "创建页面成功", "data": { "id": 1, "uuid": "8F73EF349A0911E8AB1B54EE75D2EBC1", "slug": "title-20180807-1", "title": "title-20180807-1", "body": "body-20180807-1", "view": 0, "status": 1, "created_at": 1533622648, "updated_at": 1533622648 } }
12、查看生成的 SQL 语句,符合预期
INSERT INTO `page` (`slug`, `title`, `body`, `view`, `status`, `created_at`, `updated_at`, `uuid`) VALUES ('title-20180807-1', 'title-20180807-1', 'body-20180807-1', 0, 1, 1533622648, 1533622648, '8F73EF349A0911E8AB1B54EE75D2EBC1')
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/250436.html