如何在 Symfony 4 中生成一个唯一的 ID?

How can I generate an unique id in Symfony 4?

我想创建一个唯一的 id,所以在我的 Controller.php 中,我这样写:

use Symfony\Component\Validator\Constraints\Uuid;

稍后在我的函数中:

$unique_id = $this->uuid = Uuid::uuid4();

但我收到错误消息:

Attempted to call an undefined method named "uuid4" of class "Symfony\Component\Validator\Constraints\Uuid".

您可以使用 https://packagist.org/packages/ramsey/uuid

中的 ramsey/uuid
composer require ramsey/uuid

安装后:

use Ramsey\Uuid\Uuid;

function generateUid()
{
   return Uuid::uuid4();
}

您可以查看文档以获取更多信息。

只有doctrine可以在持久化对象到数据库时自动为你生成uuid。你可以在你的实体中这样设置。

/**
 *
 * @ORM\Id
 * @ORM\Column(name="id", type="guid")
 * @ORM\GeneratedValue(strategy="UUID")
 */
protected $id;

有时这确实是一个问题,当您立即需要 uuid 以在代码中获取进一步的说明时,但您无法在那个时间点保留该对象。所以我使用这个包获得了很好的体验:

https://packagist.org/packages/ramsey/uuid

<?php

namespace YourBundle\Controller;

use Ramsey\Uuid\Uuid;

/**
 * Your controller.
 *
 * @Route("/whatever")
 */
class YourController extends Controller
{
    /**
     * @Route("/your/route", name="your_route")
     */
    public function yourFunction(Request $request)
    {
        try {
            $uuidGenerator = Uuid::uuid4();
            $uuid = $uuidGenerator->toString();
        } catch (\Exception $exception) {
            // Do something
        }
    }
}

如果您向实体添加字段并且需要为该字段自动生成 UUID,并且您已经具有自动生成的自动增量 ID,那么您可以在持久化实体之前进行生成。

use Symfony\Component\Uid\Uuid;

// ...

/**
 * @var string
 *
 * @ORM\Column(name="uuid", type="guid", unique=true)
 */
private $uuid;

/**
 * @ORM\PrePersist()
 */
public function prePersist()
{
    $this->setDateCreated($this->getDateCreated() ?: (new DateTime()));
    $this->uuid = Uuid::v4()->toRfc4122();
}

此外,您可能需要修改迁移

public function preUp(Schema $schema) : void
{
    $this->addSql('ALTER TABLE table_name ADD uuid CHAR(36) DEFAULT NULL COMMENT \'(DC2Type:guid)\'');
    $this->addSql('CREATE UNIQUE INDEX UNIQ_1C1B038BD17F50A6 ON table_name (uuid)');
}

public function up(Schema $schema) : void
{
    // this up() migration is auto-generated, please modify it to your needs
    $this->addSql('UPDATE table_name SET uuid = UUID()');
    $this->addSql('ALTER TABLE table_name CHANGE uuid uuid CHAR(36) NOT NULL COMMENT \'(DC2Type:guid)\'');
}

public function down(Schema $schema) : void
{
    // this down() migration is auto-generated, please modify it to your needs
    $this->addSql('DROP INDEX UNIQ_1C1B038BD17F50A6 ON table_name');
    $this->addSql('ALTER TABLE table_name DROP uuid');
}

这里解释一下为什么more than one autogeneration thru annotations doesn't work with Doctrine