没有不值得去解决的问题,也没有不值得去学习的技术!

Implementing UUID in the New yii2-app-advanced GitHub Repository Based on yiisoft/yii2-app-advanced

Execute the database migration, view the table structure, and regenerate the model file using Gii

1. Search for yii2 uuid on GitHub and select wartron/yii2-uuid, as shown in Figure 1

Search for yii2 uuid on GitHub and select wartron/yii2-uuid
Figure 1

2. Install via Composer, an error occurs

Bash
composer require wartron/yii2-uuid "*"

Plaintext
./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. Install via Composer, installation succeeds, as shown in Figure 2

Install via Composer, an error occurs
Figure 2

Bash
composer require wartron/yii2-uuid "dev-master"

Plaintext
./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. Create a new database migration to add a uuid field to the page model

Bash
.\yii migrate/create add_uuid_to_page

5. Edit the database migration file, \console\migrations\m180807_032326_add_uuid_to_page.php, to set uuid as a unique index

PHP
<?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. Execute the database migration, view the table structure, and regenerate the model file using Gii, as shown in Figure 3

Execute the database migration, view the table structure, and regenerate the model file using Gii
Figure 3
Bash
.\yii migrate

7. Attach the behavior wartron\yii2uuid\behaviors\UUIDBehavior, edit \common\logics\Page.php

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. In Postman, POST to http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/pages , an error occurs: iconv(): Detected an illegal character in input string

JSON
{
    "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. Implement the behavior \common\behaviors\UUIDBehavior.php, inheriting from \wartron\yii2uuid\behaviors\UUIDBehavior, to convert the binary string containing data to a hexadecimal value and transform it to uppercase

PHP
<?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. Attach the behavior common\behaviors\UUIDBehavior, edit \common\logics\Page.php

PHP
use common\behaviors\UUIDBehavior;

11. In Postman, POST to http://api.github-shuijingwan-yii2-app-advanced.localhost/v1/pages , the response is successful

JSON
{
    "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. View the generated SQL statement, which meets expectations

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')

系列导航

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系